我有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 |
+----------+
我可以在单个查询中制作吗?
答案 0 :(得分:2)
怎么样
SELECT SUM(c)
FROM
(
SELECT count(*) as c FROM base_1.users;
) x
UNION
(
SELECT count(*) as c FROM base_2.users;
) y
答案 1 :(得分:1)
您可以在两个查询之间使用UNION ALL
,然后使用SUM()
获取总数:
select sum(total) as TotalCount
from
(
SELECT count(*) Total
FROM base_1.users
UNION ALL
SELECT count(*)
FROM base_2.users
) src