显示在关系 table 中至少出现一次的行?
Show rows with at least one occurrence in a relation table?
我有以下 table 架构:
user (id, name, alias, password, active, mail, age)
comment(id, news(FK), user(FK), text, date)
new_cat(news(FK), category(FK))
我正在尝试 select 所有评论过至少一个 new
的用户category
。
这是我正在尝试但没有成功的方法:
SELECT * FROM user AS u, comment AS c
WHERE u.id = c.user AND c.news IN (SELECT news FROM new_cat);
我认为这没有正确迭代并检查每个 category
并且只检查条件是否仅适用于一个 category
.
我怎样才能正确地做到这一点?
加入table组,按用户分组,在HAVING
子句中设置条件
如果有一个 category
table 用于存储所有类别:
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);
我有以下 table 架构:
user (id, name, alias, password, active, mail, age)
comment(id, news(FK), user(FK), text, date)
new_cat(news(FK), category(FK))
我正在尝试 select 所有评论过至少一个 new
的用户category
。
这是我正在尝试但没有成功的方法:
SELECT * FROM user AS u, comment AS c
WHERE u.id = c.user AND c.news IN (SELECT news FROM new_cat);
我认为这没有正确迭代并检查每个 category
并且只检查条件是否仅适用于一个 category
.
我怎样才能正确地做到这一点?
加入table组,按用户分组,在HAVING
子句中设置条件
如果有一个 category
table 用于存储所有类别:
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);