简体   繁体   English

在关系表中显示至少出现一次的行?

[英]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.

相关问题 从表中删除至少一个值为 NULL 的行 - Delete rows from table where at least one of the values is NULL SQL计算一个表相对于另一表的行 - SQL count rows of one table in relation to another table 在表中查找行关系 - Finding rows relation in a table 如何在具有不同行的多对一关系字典表中拥有? - How to have in many-to-one relation dictionary table with distinct rows? SQL - 获取具有一个结果和选定选项的行 - 关系表 - SQL - Get rows with one result and selected option - Relation Table 如何关联一个相关表行中的某些行? - How to relation some rows from one related table row? 返回与另一个表中的所有行至少有一个引用的所有行 - Return all rows that have at least one reference with all the rows in another table 查询以查找一组列中至少一个值的出现 - Query to find occurrence of at least one value in a set of columns SQL - 仅在具有一个或多个选项的表上选择具有一个结果的行 - 关系表 - SQL - Select only rows with one result on table with one or multiple options - Relation Table 从表中选择满足子表中所有在另一表中至少有一条记录的所有行的条件的行 - Select rows from a table satisfying criteria for all rows in a child table which have at least one record in another table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM