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)
字段名称非常不言自明。我想选择同时具有 1 个和 3 个 tag_id
的 post_id
,因此在本例中只有 1
。我想到了类似的东西 SELECT post_id FROM Tags GROUP BY post_id HAVING ...
拥有后,我想列出该组中存在的tag_id
。我该怎么做?
Say there is such table:
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)
Field names are pretty self-explanatory. I want to select post_id
s that have both 1 and 3 tag_id
s, so in this example it's only 1
. I thought of something likeSELECT post_id FROM tags GROUP BY post_id HAVING ...
After having I'd like to list tag_id
s that are present in this group. How do I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果没有任何唯一约束,请尝试:
或者使用此
HAVING
子句,如果尝试仅检测两个tag_id
值:如果 post_id 和 tag_id 都有唯一约束,则此也应该有效:
If there aren't any unique constraints try:
Or use this
HAVING
clause, if trying to detect only twotag_id
values:If post_id and tag_id both have an unique constraint, this should work too:
您可以尝试自连接(N tag_id -> N join),但可能速度不快
You could try a self join (N tag_id -> N join) but probably it's not fast
将 GROUP_CONCAT() 用于问题的第二部分
Use GROUP_CONCAT() for the second part of your question
我对你的其他桌子做了一些假设。 (即,您有一个我称为
posts
的帖子表和一个以 tag_id 作为 PK 的表,我将其称为tag_table
以避免与 posts/tags 表发生名称冲突我可以看到您已经调用了tags
)您想要列表 {1,3} 中不存在标签的帖子,而列表 {1,3} 中不存在与相应 post_id/tag_id 相匹配的记录,因此您可以使用双 NOT EXISTS 构造,如下所示。
另一种替代方法是使用 Group By 和 Count。 A对此问题的解决方法的回顾在这里。
I've made some assumptions about your other tables. (i.e. that you have a table for posts that I have called
posts
and one with tag_id as the PK which I have calledtag_table
to avoid a nameclash with the posts/tags table that I can see you already calltags
)You want posts where there does not exist a tag in the list {1,3} for which there does not exist a matching record with the corresponding post_id/tag_id so you can use a double NOT EXISTS construct as below.
Another alternative approach is to use Group By and Count. A review of approaches to this problem is here.
怎么样
How about
@Keeper 解决方案的 WHERE 版本
WHERE version of @Keeper's solution