有效地查询多对多查找X与Y无关

时间:2018-02-13 16:52:36

标签: mysql many-to-many

我有多对多的数据透视表供评论,例如:

user_id | post_id | comment 234 | 123 | "This project is awesome" 235 | 123 | "This is so cool!" 234 | 124 | "I really like the look of this one" 235 | 124 | "What are you going to make next?" 235 | 125 | "So cool to finally see this!"

我需要编写一个查询来从未对特定帖子发表评论的用户中选择*。我能想到的最好的方法是使用子选择的查询,如下所示:

SELECT * FROM users WHERE id NOT IN (SELECT user_id FROM comments WHERE post_id IN (123,125))

这感觉效率低下(很大程度上是由于子选择),我试图找到一个更好的查询来执行此操作。还有另一种方法吗?

1 个答案:

答案 0 :(得分:-1)

您可以使用数据透视表替换数据透视表:

select u.* from users u left join pivot p on u.id = p.user_id
group by u.id` having count(case when p.post_id in (123,125) then 1 else 0 end) =0