将COUNT和GROUP BY与多个JOIN表一起使用

时间:2017-10-20 14:18:41

标签: mysql sql mariadb

我希望使用JOIN

COUNT多个表并需要来自多个表的GROUP BY

表格不像这样

表A

a_id | name          
------------         
1    | john           
2    | david
3    | anna

表B

b_id | b_title
--------------
1    | b1     
2    | b2     
3    | b3     

表C

c_id | c_title | b_id
------------------------
1    | c1      | 2
2    | c2      | 3
3    | c3      | 1
4    | c4      | 1

表D

d_id | d_title | c_id | a_id | cost
-----------------------------------
1    | d1      | 3    | 1    | 200
2    | d2      | 1    | 1    | 130
3    | d3      | 2    | 2    | 240
4    | d4      | 2    | 3    | 170
5    | d5      | 4    | 1    | 95

我想要的是这样的

name | COUNT(b_id) | COUNT(d_id) | SUM(cost)
--------------------------------------------
john |      2      |      3      |   425
david|      1      |      1      |   240 
anna |      1      |      1      |   170

这是我的查询

SELECT a.name, COUNT(d.d_id), SUM(cost)
FROM a INNER JOIN d ON a.a_id = d.a_id
GROUP BY a.a_id

我尝试过,但无法获得COUNT(b_id)

的正确结果

2 个答案:

答案 0 :(得分:2)

您想要计算不同的b_id

SELECT
  a.name, 
  COUNT(DISTINCT c.b_id),
  COUNT(d.d_id),
  SUM(d.cost)
FROM d 
JOIN a ON a.a_id = d.a_id
JOIN c ON c.c_id = d.c_id
GROUP BY a.a_id;

答案 1 :(得分:0)

只需向表JOIN添加额外的c,就像这样:

SELECT a.name, COUNT(d.d_id), COUNT(b_id), SUM(cost)
FROM a 
INNER JOIN d ON a.a_id = d.a_id
INNER JOIN c ON c.b_id = d.c_id
GROUP BY a.a_id, a.name