假设有这样一个表:
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 的 stag_id
s,所以在这个例子中它只是1
。我想到了类似的事情SELECT post_id FROM tags GROUP BY post_id HAVING ...
有了之后我想列出tag_id
该组中存在的 s。我怎么做?
如果没有任何独特的约束,请尝试:
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
values:
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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)