MySQL查询计数与子类型

时间:2016-04-12 09:03:53

标签: mysql

我想知道是否有人可以提供帮助

我有以下表格

user_ids {
    uUID
    name
}

types {
    tUID
    name
}

activity {
    aUID
    user_id
    type_id
    date
}

因此用户将包含

uUID    name
1       Bob
2       Mark
3       Peter

类型将是

tUID    name
1       Baseball
2       Football
3       Cricket

活动将是

aUID    user_id    type_id    date
1         1           2
2         1           2
3         1           3
4         2           1
5         2           3
6         2           1
7         3           3
8         3           3
9         3           3

现在我想得到的是下表

Name   Type      Count of type
Bob    Baseball  0
Bob    Football  2
Bob    Cricket   1
Mark   Baseball  2
Mark   Football  0
Mark   Cricket   1
Peter  Baseball  0
Peter  Football  0
Peter  Cricket   3

我可以使用单个查询的每个用户ID执行此操作,但想知道是否有办法使用单个查询来执行此操作。

由于

马丁

3 个答案:

答案 0 :(得分:4)

试试这个

SELECT X.Name ,X.Type,
SUM(CASE WHEN A.user_id IS NULL THEN 0 ELSE 1 END ) as `Count of type`
FROM
(
    SELECT T.Name AS Type,U.name AS NAME,U.uUID,T.tuid FROM types T,user_ids U
)X  LEFT JOIN activity A ON A.type_id = X.tuid AND A.user_id =X.uUID
GROUP BY X.Name ,X.Type
ORDER BY X.Name ,X.Type

没有零

SELECT U.name AS Name, 
       T.name AS Type, 
       SUM(CASE WHEN A.user_id IS NULL THEN 0 ELSE 1 END ) as `Count of type`
FROM types T
LEFT JOIN activity a on T.tuid=A.type_id
JOIN user_ids U on A.user_id = U.uUID
GROUP BY U.name, T.name

答案 1 :(得分:2)

您只需要离开联接类型​​和活动表并按用户分组并输入:

select u.name as Name, t.name as Type, COUNT(a.user_id) as `Count of type`
from type t
left join activity a on t.tuid=a.type_id
left join users u on a.user_id = u.uUID
group by u.name, t.name

答案 2 :(得分:0)

解决方案是使用CROSS JOIN userstypes的{​​{1}},然后是LEFT JOIN activity

select u.name as Name, t.name as Type, COUNT(a.aUID) as `Count of type`
from users u CROSS JOIN type t
    LEFT JOIN activity a ON a.user_id = u.uUID AND a.type_id = t.tUID