我正在尝试计算以下三个结果的总和,但我只计算一个结果。
$sql = "(SELECT COUNT(*) FROM table1 WHERE somecondition)
UNION
(SELECT COUNT(*) FROM table2 WHERE somecondition)
UNION
(SELECT COUNT(*) FROM table3 WHERE somecondition)";
任何人都可以帮忙。谢谢
答案 0 :(得分:5)
您的查询将返回三行,其中包含三个单独的计数。
你想要的是
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
答案 1 :(得分:0)
你可以尝试这样的事情......
SELECT sum(
( SELECT count(*) from table1)
+ ( SELECT count(*) from table2)
+ ( SELECT count(*) from table3)
+ ( SELECT count(*) from table4) )as total from dual
答案 2 :(得分:0)
如果您正在寻找每个表的计数作为不同的字段..
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
答案 3 :(得分:-1)
您的查询将返回3行 - 每个表用于表。
请改用此查询:
$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)
)";
(您需要根据您使用的数据库调整查询)