一尘不染

MySQL:如何选择具有特定值的组?

mysql

说有这样的表:

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)

字段名称很容易解释。我想选择post_id同时具有1和3 tag_id的,因此在此示例中仅1。我想到了类似的 SELECT post_id FROM tags GROUP BY post_id HAVING ...清单tag_id,之后我想列出该组中存在的。我怎么做?


阅读 311

收藏
2020-05-17

共1个答案

一尘不染

如果没有任何唯一约束,请尝试:

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;
2020-05-17