我有三张桌子
发布
id | statement | date
功能
id | feature
post_feature (帖子和功能之间的多对多表格)
post_id | feature_id
我想触发一个查询,该查询将为我提供给定日期期间的帖子的不同特征及其各自功能的计数。我刚开始学习SQL,但我无法解决这个问题。
我尝试了以下但没有得到正确的结果。
SELECT f.feature, count(f.feature)
FROM post_feature l
JOIN features f ON (l.featureid = f.id AND l.featureid IN (
select post.id from post where post.date > 'some_date'))
GROUP BY f.feature
答案 0 :(得分:9)
您可以尝试这样:
SELECT f.feature, count(f.feature)
FROM post_feature l
JOIN features f ON l.featureid = f.id
JOIN post p ON l.post_id =p.id
WHERE p.date > 'some_date'
GROUP BY f.feature
答案 1 :(得分:2)
select f.feature, count(*)
from post_feature l inner join features f on l.feature_id = f.id
inner join post p on l.post_id = p.id
where p.date > 'some_date'
group by f.feature
答案 2 :(得分:2)
您的SQL非常有创意。但是,您在IN子句中的连接位于错误的列上。它应该是postid to postid。
虽然这会修复查询,但这是一种更好的编写方式:
SELECT f.feature, count(f.feature)
FROM post p join
post_feature pf
on p.id = pf.postid join
feature f
on pf.featureid = f.id
where post.date > 'some_date'
GROUP BY f.feature
这会加入所有表格,然后根据您想知道的信息进行汇总。
答案 3 :(得分:0)
尝试
SELECT f.feature, count(DISTINCT f.feature)
FROM post_feature l
JOIN features f ON (l.featureid = f.id AND l.featureid IN (
select post.id from post where post.date > 'some_date'))
GROUP BY f.feature