如何计算与单个查询中的基表结果匹配的多个表的记录?

时间:2018-01-26 02:48:41

标签: mysql sql

下面的查询返回过程表的所有名称和table1中匹配结果的计数,如下所示:

SELECT p.name, COUNT(t1.id) as Quantity
FROM procedures p
LEFT JOIN table1 t1
ON p.id = t1.id
GROUP BY p.name ASC

如何进行上述查询,但要计算许多其他表?想象一下,我还有2个表需要计算,查询输出这样的列:

Name Quantity1 Quantity2 Quantity3
A        0       100        27
B        10      0          15
C        50      200        1

程序表:

id   name
1     A
2     B
3     C

我想根据程序计算匹配结果的其他表

table1,table2,table3 ...

id   name
1     A
1     A
1     A
2     B
2     B
3     C
3     C

2 个答案:

答案 0 :(得分:0)

加入其他表格:

SELECT p.name, 
       COUNT(t1.id) as Quantity1, 
       COUNT(t2.id) as Quantity2,
       COUNT(t3.id) as Quantity3
FROM   procedures p
       LEFT JOIN table1 t1 ON p.id = t1.id
       LEFT JOIN table2 t2 ON p.id = t2.id
       LEFT JOIN table3 t3 ON p.id = t3.id
GROUP  BY p.name ASC

答案 1 :(得分:0)

最好的方法可能是在join之前聚合:

SELECT p.name, SUM(t1.cnt1) as cnt1
FROM procedures p LEFT JOIN
     (SELECT t1.id, COUNT(*) as cnt1
      FROM table1 t1
      GROUP BY t1.id
     ) t1
     ON p.id = t1.id
GROUP BY p.name ASC;

嗯,如果nameid不是1-1,你仍然会得到重复。如果这是一个问题,那么:

SELECT p.name, t1.cnt1 as cnt1
FROM (SELECT DISTINCT name
      FROM procedures p
     ) p LEFT JOIN
     (SELECT p.name, COUNT(*) as cnt1
      FROM table1 t1 JOIN
           procedures p
           ON p.id = t1.id
      GROUP BY p.name
     ) t1
     ON p.name = t1.name;

这种方法将安全推广。