2012-12-20 45 views
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 | 
+----------+ 

我可以在單個查詢嗎?

回答

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 
2

如何

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