对多个ID中的每一个计算多个表的行数

时间:2015-01-25 16:00:10

标签: mysql vba

我写了一个sql查询来计算(在三个表上)与Id相关的行:

SELECT 
(SELECT `Id` FROM `Tab1` WHERE `Id` = '1') AS ID, 
(SELECT COUNT(*) FROM `tab1` WHERE `Id` = '1') AS RowsTab1,
(SELECT COUNT(*) FROM `tab2` WHERE `Id` = '1') AS RowsTab2,
(SELECT COUNT(*) FROM `tab3` WHERE `Id` = '1') AS RowsTab3

但我需要在Ids数组上使用它,以便查询结果是一个表,对于每个Id,显示三个表中每个表中有多少行。

结果应该是这样的:

ID    RowsTab1     RowsTab2     RowsTab3
 1        2            4            2
 2        3            0            8
 5        0            2            4

等等

有没有办法只用一个查询来完成它?

我想澄清一下,查询将使用Excel - VBA

执行

提前致谢

2 个答案:

答案 0 :(得分:1)

您可以使用相关子查询获得所需的计数。然后,您需要ids的源,您可以将其放入子查询中。像这样:

select ids.id,
       (select count(*) from tabl where tabl1.id = ids.id) as tab1_cnt,
       (select count(*) from tab2 where tabl2.id = ids.id) as tab2_cnt,
       (select count(*) from tab3 where tabl3.id = ids.id) as tab3_cnt
from (select 1 as id union all select 2 union all select 5) as ids

如果您关心的ID已经在表格中,那么您可以使用该表格。

答案 1 :(得分:0)

如果我理解正确,这可以解决您的问题:

SELECT Tab0.id,
(SELECT COUNT(*) FROM `tab1` WHERE `Id` = Tab0.Id) AS RowsTab1,
(SELECT COUNT(*) FROM `tab2` WHERE `Id` = Tab0.Id) AS RowsTab2,
(SELECT COUNT(*) FROM `tab3` WHERE `Id` = Tab0.Id) AS RowsTab3
FROM Tab0 WHERE field1 = 'myvalue'