2010-09-21 109 views
28

如何從MySQL中的多個表中選擇COUNT(*)?MySQL中多個表的COUNT(*)

如:

SELECT COUNT(*) AS table1Count FROM table1 WHERE someCondition 
JOIN?? 
SELECT COUNT(*) AS table2Count FROM table2 WHERE someCondition 
CROSS JOIN? subqueries? 
SELECT COUNT(*) AS table3Count FROM table3 WHERE someCondition 

編輯:

的目標是回到這樣的:

+-------------+-------------+-------------+ 
| table1Count | table2Count | table3Count | 
+-------------+-------------+-------------+ 
| 14   | 27   | 0   | 
+-------------+-------------+-------------+ 
+0

你叫什麼目標? – Scott 2010-09-21 14:21:36

+0

需要更多細節 - 你能用文字描述你想要做什麼嗎? – egrunin 2010-09-21 14:22:01

+0

嘗試將內部連接更改爲左側連接 – 2010-09-21 14:31:16

回答

65

您可以通過使用子查詢每個TableCount的做到這一點,一個子查詢:

SELECT 
    (SELECT COUNT(*) FROM table1 WHERE someCondition) as table1Count, 
    (SELECT COUNT(*) FROM table2 WHERE someCondition) as table2Count, 
    (SELECT COUNT(*) FROM table3 WHERE someCondition) as table3Count 
+0

我想從第一個計數行開始計數3(計數)行,並且只計算第二個計數行的計數行數。我該怎麼做? – Adrian 2015-02-27 11:14:57

+1

我來這裏試圖找出如何在firebird數據庫中做同樣的事情。語法略有不同:SELECT * FROM (SELECT COUNT(*)AS table1Count FROM table1), (SELECT COUNT(*)AS table2Count FROM table2), (SELECT COUNT(*)AS table3Count FROM table3) – 2017-02-18 14:38:42

2

您可以使用UNION

SELECT COUNT(*) FROM table1 WHERE someCondition 
    UNION 
    SELECT COUNT(*) FROM table2 WHERE someCondition 
    UNION 
    SELECT COUNT(*) FROM table3 WHERE someCondition 
+3

聯合將在單獨的行中顯示結果,而不是列。 OP所要查找的結果集是一個包含3個計數列的單行 – 2010-09-21 15:19:34

10

你可以用子查詢做到這一點,如:

select (SELECT COUNT(*) FROM table1 WHERE someCondition) as table1Count, 
     (SELECT COUNT(*) FROM table2 WHERE someCondition) as table2Count 
3

嘗試改用:

SELECT 
    COUNT(table1.*) as t1, 
    COUNT(table2.*) as t2, 
    COUNT(table3.*) as t3 
FROM table1 
    LEFT JOIN tabel2 ON condition 
    LEFT JOIN tabel3 ON condition 
+0

在表格之間沒有關係 – 2015-11-28 13:33:10