假设有这样一张表:
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: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
复制相似问题