在单个查询中来自多个基的计数。

时间:2020-12-07 08:22:04

I have 2 MySQL databases i want to count number of rows in two tables on each database and combine results.

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

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

This query return result of first count.

该查询返回第一次计数的结果。

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

Can i make it in single query ?

我可以用一个查询吗?

2 个解决方案

#1


1  

You can use a UNION ALL between the two queries and then use SUM() to get the total:

您可以在两个查询之间使用一个UNION,然后使用SUM()来获得total:

select sum(total) as TotalCount
from
(
  SELECT count(*) Total
  FROM base_1.users
  UNION ALL
  SELECT count(*) 
  FROM base_2.users
) src

#2


2  

How about

如何

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  

You can use a UNION ALL between the two queries and then use SUM() to get the total:

您可以在两个查询之间使用一个UNION,然后使用SUM()来获得total:

select sum(total) as TotalCount
from
(
  SELECT count(*) Total
  FROM base_1.users
  UNION ALL
  SELECT count(*) 
  FROM base_2.users
) src

#2


2  

How about

如何

SELECT SUM(c)
FROM 
(
   SELECT count(*) as c FROM base_1.users;
) x
UNION
(
   SELECT count(*) as c FROM base_2.users;
) y