假设有这样一张表:
mysql> SELECT * FROM tags;
+---------+--------+
| post_id | tag_id |
+---------+--------+
|       1 |      2 |
|       1 |      3 |
|       1 |      1 |
|       2 |      1 |
|       2 |      2 |
+---------+--------+
5 rows in set (0.00 sec)字段名称非常简单明了。我希望选择既有1个tag_id又有3个1的post_id,因此在本例中它只有1。在我想列出这个组中存在的tag_id之后,我想到了像SELECT post_id FROM tags GROUP BY post_id HAVING ...这样的东西。我该怎么做?
发布于 2010-06-21 17:47:04
如果没有任何唯一约束,请尝试:
SELECT post_id 
FROM tags 
WHERE tag_id = 1 OR tag_id = 3 
GROUP BY post_id 
HAVING count(DISTINCT tag_id) = 2;如果尝试仅检测两个tag_id值,则使用此HAVING子句:
HAVING MIN(tag_id) <> MAX(tag_id)如果post_id和tag_id都有一个唯一的约束,这也应该是可行的:
SELECT post_id 
FROM tags 
WHERE tag_id = 1 OR tag_id = 3 
GROUP BY post_id 
HAVING count(*) = 2;发布于 2010-06-21 17:34:49
您可以尝试自连接(N tag_id -> N join),但它可能不快
SELECT t1.post_id 
FROM tags t1 INNER JOIN tags t2 ON t1.post_id = t2.post_id 
WHERE t1.tag_id = 1 AND t2.tag_id = 3发布于 2010-06-21 17:44:29
SELECT post_id
  FROM ( SELECT post_id,
                count(tag_id) AS counter
           FROM tags
          WHERE tag_id IN (1,3)
          GROUP BY post_id
       )
 WHERE counter = 2对问题的第二部分使用GROUP_CONCAT()
SELECT post_id,
       GROUP_CONCAT(tag_id ORDER BY tag_id ASC SEPARATOR ',')
  FROM tagshttps://stackoverflow.com/questions/3083409
复制相似问题