如何在一个SQL查询中计算来自多个表的行

时间:2019-01-16 06:33:40

标签: mysql

我遇到一个问题,必须从多个表中获取行计数。

例如:

SELECT COUNT(*) FROM table1;
SELECT COUNT(*) FROM table1 where condition;
SELECT COUNT(*) FROM table2;
SELECT COUNT(*) FROM table3 where condition;

1 个答案:

答案 0 :(得分:2)

您可以使用UNION

SELECT COUNT(*) FROM table1
UNION
SELECT COUNT(*) FROM table1 where condition;
UNION
SELECT COUNT(*) FROM table2;
UNION
SELECT COUNT(*) FROM table3 where condition;

您可以添加额外的字段,以通过以下查询找到要获取的行

SELECT "COND-1" AS TITLE, COUNT(*) FROM table1
UNION
SELECT "COND-2" AS TITLE, COUNT(*) FROM table1 where condition;
UNION
SELECT "COND-3" AS TITLE, COUNT(*) FROM table2;
UNION
SELECT "COND-4" AS TITLE, COUNT(*) FROM table3 where condition;