我有多对多关系,我想找到所有W和他们在某个日期创建的A的总和(频率)。 最好的方法是什么?
结果 NOT 应为:
w.name | sum
-------+------
bar | 2
bar | 5
baz | 4
bim | 3
foo | 2
foo | 3
结果应为:
w.name | sum
-------+------
bar | 7
baz | 4
bim | 3
foo | 5
我的桌子:
表A:
id | title | author | created_at
----+-------+--------+-------------
... | ... | ... | ...
11 | abc | ccc | Thu, 5 Apr 2012 08:01:25 GMT
12 | bcb | ddd | Thu, 5 Apr 2012 10:11:15 GMT
13 | dfg | aaa | Fri, 6 Apr 2012 07:33:45 GMT
表AW:
id | aid | wid | freq
----+-----+-----+------
... | ... | ... | ...
201 | 11 | 2 | 2
202 | 11 | 3 | 4
203 | 11 | 17 | 2
204 | 12 | 17 | 3
205 | 12 | 66 | 1
206 | 12 | 12 | 2
207 | 12 | 24 | 5
208 | 12 | 7 | 3
209 | 13 | 2 | 5
210 | 13 | ... | ...
表W:
id | name | ...
----+-------+--------
... | ... | ...
2 | bar | ...
3 | baz | ...
... | ... | ...
7 | bim | ...
... | ... | ...
17 | foo |
答案 0 :(得分:1)
对于每个W
,今天创建A
的频率总和:
select W.name
, sum(AW.frequency)
from A
join AW
on AW.aid = a.id
join W
on W.id = AW.bid
where '2012-04-08' < A.created_at and A.created_at < '2012-04-09'
group by
W.name
答案 1 :(得分:1)
SELECT w.name, SUM(aw.frequency)
FROM a INNER JOIN aw ON (a.id = aw.aid)
INNER JOIN w ON (aw.wid = w.id)
WHERE a.created_at >= INITIAL_DATE and a.created_at <= END_DATE
GROUP BY w.name