计数(*)多个表

时间:2011-11-09 20:33:36

标签: mysql sql count

我正在浏览从多个表中获取计数的解决方案,我遇到了以下答案:

SELECT COUNT(*),(SELECT COUNT(*) FROM table2) FROM table1

它的效果很好,但我似乎无法让它超过2个表。我目前的代码如下:

SELECT COUNT(*), 
(SELECT COUNT(*) FROM TABLE1),
(SELECT COUNT(*) FROM TABLE2),
(SELECT COUNT(*) FROM TABLE3),
(SELECT COUNT(*) FROM TABLE4),
(SELECT COUNT(*) FROM TABLE5),
(SELECT COUNT(*) FROM TABLE6),
(SELECT COUNT(*) FROM TABLE7),
(SELECT COUNT(*) FROM TABLE8),
(SELECT COUNT(*) FROM TABLE9),
(SELECT COUNT(*) FROM TABLE10),
(SELECT COUNT(*) FROM TABLE11),
(SELECT COUNT(*) FROM TABLE12),
(SELECT COUNT(*) FROM TABLE13),
(SELECT COUNT(*) FROM TABLE14),
(SELECT COUNT(*) FROM TABLE15),
(SELECT COUNT(*) FROM TABLE16),
(SELECT COUNT(*) FROM TABLE17),
(SELECT COUNT(*) FROM TABLE18)
FROM TABLE19

但是,它只计算TABLE1和TABLE19。我需要计算所有表(TABLE1-18)以及TABLE19(希望使用类似于第一个示例的结构)。

4 个答案:

答案 0 :(得分:2)

使用别名以使列具有唯一名称:

SELECT 
    (SELECT COUNT(*) FROM TABLE1) AS count_table1,
    (SELECT COUNT(*) FROM TABLE2) AS count_table2,
    (SELECT COUNT(*) FROM TABLE3) AS count_table3,
    etc..
    (SELECT COUNT(*) FROM TABLE19) AS count_table19

答案 1 :(得分:2)

根据哪个数据库,它可能会稍微改变......

对于Oracle,请执行以下操作:

Select (select count(*) from table1) as table1Count, 
       (select count(*) from table2) as table2Count
from dual

如果它是SQL Server,那么就离开双重。

编辑:

由于您提到您在评论中使用MySQL:

Get record counts for all tables in MySQL database

答案 2 :(得分:0)

如果您乐于接受行而不是列的结果,则可以始终使用UNION:

SELECT "table1", COUNT(*) FROM table1 UNION                         
SELECT "table2", COUNT(*) FROM table2 UNION                         
SELECT "table3", COUNT(*) FROM table3

等。

答案 3 :(得分:0)

在MySQL上,这有效:

select sum(total) from(
select count(*) as total from Table1 
union
select count(*) as total from Table2) as a;