简体   繁体   中英

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 .

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 .

How can I properly do this?

Join the tables, group by user and set the condition in the HAVING clause.

If there is a category table where you store all the categories:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM