我想要計算以下所有三個結果的總和,但我只能計算一個結果。選擇計數(*)不會給出正確的計數
$sql = "(SELECT COUNT(*) FROM table1 WHERE somecondition)
UNION
(SELECT COUNT(*) FROM table2 WHERE somecondition)
UNION
(SELECT COUNT(*) FROM table3 WHERE somecondition)";
任何人都可以help.thanks
我想要計算以下所有三個結果的總和,但我只能計算一個結果。選擇計數(*)不會給出正確的計數
$sql = "(SELECT COUNT(*) FROM table1 WHERE somecondition)
UNION
(SELECT COUNT(*) FROM table2 WHERE somecondition)
UNION
(SELECT COUNT(*) FROM table3 WHERE somecondition)";
任何人都可以help.thanks
您的查詢將返回三人行,用三個獨立的罪名。
你想要的是
select sum(c) from (
(SELECT COUNT(*) AS c FROM table1 WHERE somecondition)
UNION
(SELECT COUNT(*) FROM table2 WHERE somecondition)
UNION
(SELECT COUNT(*) FROM table3 WHERE somecondition)
) all_three
您的查詢將返回3 rows-爲每個表。
使用此查詢,而不是:
$sql = "SELECT SUM(C) FROM(
(SELECT COUNT(*) as C FROM table1 WHERE somecondition)
UNION
(SELECT COUNT(*) as C FROM table2 WHERE somecondition)
UNION
(SELECT COUNT(*) as C FROM table3 WHERE somecondition)
)";
(您需要調整,這取決於你所使用的數據庫查詢)
我正在使用mysql,我是一個新手,學習mysql/php。我上面嘗試過,但仍然沒有工作,我錯過了什麼? – sanjay 2012-04-27 05:25:18
你可以嘗試這樣的事情....
SELECT sum(
(SELECT count(*) from table1)
+ (SELECT count(*) from table2)
+ (SELECT count(*) from table3)
+ (SELECT count(*) from table4))as total from dual
此查詢正在運行並正在運行 – Addicted 2012-04-27 05:30:35
如果您正在尋找作爲不同領域的每張桌子的計數...
SELECT (SELECT count(*) FROM table_1) As first_count,
(SELECT count(*) FROM table_2) As second_count,
(SELECT count(*) FROM table_3) As third_count
如果要總結所有3代表的所有計數然後
SELECT SUM ((SELECT count(*) FROM table_1) +
(SELECT count(*) FROM table_2) +
(SELECT count(*) FROM table_3)) AS total_count
+1,不要忘記派生表的別名。 – 2012-04-27 05:15:08
@PaulBellora:謝謝。像這樣? – Thilo 2012-04-27 05:16:48
完美! http://sqlfiddle.com/#!2/82ed0/8 – 2012-04-27 05:18:39