[英]Show rows with at least one occurrence in a relation table?
I have the following table schema:我有以下表架构:
user (id, name, alias, password, active, mail, age)
comment(id, news(FK), user(FK), text, date)
new_cat(news(FK), category(FK))
I'm trying to select all the users who have commented on AT LEAST one new
of EVERY category
.我正在尝试选择所有评论过至少一个
new
的每个category
的用户。
This is what I'm trying without any success:这就是我没有成功的尝试:
SELECT * FROM user AS u, comment AS c
WHERE u.id = c.user AND c.news IN (SELECT news FROM new_cat);
I believe this is not iterating properly and checking for EVERY category
and just checks if the condition applies just on one category
.我相信这没有正确迭代并检查每个
category
,只是检查条件是否仅适用于一个category
。
How can I properly do this?我怎样才能正确地做到这一点?
Join the tables, group by user and set the condition in the HAVING
clause.加入表,按用户分组并在
HAVING
子句中设置条件。
If there is a category
table where you store all the categories:如果有一个存储所有类别的
category
表:
SELECT u.*
FROM user u
INNER JOIN comment c ON c.user = u.id
INNER JOIN new_cat n ON n.news = c.news
GROUP BY u.id
HAVING COUNT(DISTINCT n.category) = (SELECT COUNT(*) FROM category);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.