说有这样的表:
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和3个
post_id
的tag_id
,因此在此示例中,它仅是1
。我想到了类似的东西SELECT post_id FROM tags GROUP BY post_id HAVING ...
在我想列出该组中存在的tag_id
后。我怎么做?
最佳答案
如果没有任何唯一约束,请尝试:
SELECT post_id
FROM tags
WHERE tag_id = 1 OR tag_id = 3
GROUP BY post_id
HAVING count(DISTINCT tag_id) = 2;
或者,如果尝试仅检测两个
HAVING
值,请使用此tag_id
子句: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;
关于sql - MySQL:如何选择具有特定值的组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56724561/