1

我正在尝试计算以下所有三个结果的总和,但我只计算一个结果。

$sql = "(SELECT COUNT(*) FROM  table1 WHERE somecondition)
UNION
(SELECT COUNT(*) FROM  table2 WHERE somecondition)
UNION
(SELECT COUNT(*) FROM  table3 WHERE somecondition)";

任何人都可以帮忙。谢谢

4

4 回答 4

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
于 2012-04-27T05:12:28.957 回答
0

你可以试试这样的......

SELECT sum(
 ( SELECT count(*) from table1)
+ ( SELECT count(*) from table2)
+ ( SELECT count(*) from table3)
+ ( SELECT count(*) from table4) )as total from dual
于 2012-04-27T05:15:36.500 回答
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
于 2012-04-27T13:39:35.063 回答
-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)
)";

(您需要根据您使用的数据库调整查询)

于 2012-04-27T05:13:58.487 回答