14

好的,所以我有 4 张桌子。

users具有列id和的表name

包含和groups列的表。idnameowner

items具有列group和的表content

包含和content列的表。idnameduration

每个用户可以有几个组。每个组里面可以有几个项目。每个项目代表一个内容片段。

我希望能够列出所有组,以及该组内每条内容的所有持续时间的总和

我一直在尝试的是:

select groups.id,groups.name,users.name,sum(content.duration) as duration from groups
join users on groups.owner=users.id
join items on items.group=groups.id
join content on content.id=items.content

不幸的是,这只给了我一个结果,即所有组中每条内容的所有持续时间的总和 - 如下所示:

"g001", "Group 1", "Me", "400"

我期待的是这样的:

"g001", "Group 1", "Me", "160"
"g002", "Group 2", "You", "160"
"g003", "Group 3", "Them", "80"
4

3 回答 3

19

试试这个

   select groups.id,groups.name,users.name,sum(content.duration) as duration from groups
   join users on groups.owner=users.id
   join items on items.group=groups.id
   join content on content.id=items.content
   group by groups.name
于 2013-02-08T13:28:29.293 回答
1

试试这个:

select groups.id,groups.name,users.name,sum(content.duration) as duration
from groups
    join users
        on groups.owner=users.id
    join items
        on items.group=groups.id
    join content
        on content.id=items.content
group by groups.id,groups.name,users.name
于 2013-02-08T13:27:02.153 回答
1

LEFT JOIN即使没有内容,您也可以显示所有组,但总价值duration为零

SELECT  a.id, a.name GroupName, 
        d.name OwnerName,
        SUM(c.duration) totals
FROM    groups a
        INNER JOIN users d
            ON a.owner = d.id
        LEFT JOIN items b
            ON a.id = b.group
        LEFT JOIN content c
            ON b.content = c.id
GROUP   BY a.id, a.name, d.name
于 2013-02-08T13:28:15.650 回答