5

我有三张桌子

邮政

id | statement | date

特征

id | feature

post_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
4

4 回答 4

10

你可以这样尝试:

       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
于 2012-09-16T17:31:17.273 回答
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
于 2012-09-16T17:31:49.600 回答
2

你的 SQL 很有创意。但是,您在 IN 子句中的联接位于错误的列上。它应该在 postid 到 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

这将连接所有表,然后按您想知道的信息进行汇总。

于 2012-09-16T17:32:43.023 回答
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 
于 2012-09-16T17:31:33.713 回答