3

我有 2 个 MySQL 数据库,我想计算每个数据库上两个表中的行数并组合结果。

SELECT count(*) FROM base_1.users;
+----------+
| count(*) |
+----------+
|       15 |
+----------+
SELECT count(*) FROM base_2.users;
+----------+
| count(*) |
+----------+
|       75 |
+----------+

此查询返回第一个计数的结果。

SELECT count(*) FROM base_1.users, base_2.users;
+----------+
| count(*) |
+----------+
|       15 |
+----------+

我可以在单个查询中完成吗?

4

2 回答 2

2

怎么样

SELECT SUM(c)
FROM 
(
   SELECT count(*) as c FROM base_1.users;
) x
UNION
(
   SELECT count(*) as c FROM base_2.users;
) y
于 2012-12-20T13:42:31.847 回答
1

您可以UNION ALL在两个查询之间使用 a ,然后使用SUM()来获取总数:

select sum(total) as TotalCount
from
(
  SELECT count(*) Total
  FROM base_1.users
  UNION ALL
  SELECT count(*) 
  FROM base_2.users
) src
于 2012-12-20T13:44:58.393 回答