mySQL选择计数,多个表

时间:2011-04-07 07:04:21

标签: php mysql

我有三张桌子:

table1, table2, table3

我试图从每个表中获取总行数以及价格列的总和,例如:

$r['count'] = total rows of all 3 tables combined;
$r['price'] = sum of all prices added together in all 3 tables combined;

这是我的问题:

SELECT COUNT(*) AS `count`, SUM(price) AS `price` FROM `table1` UNION
SELECT COUNT(*) AS `count`, SUM(price) AS `price` FROM `table2` UNION
SELECT COUNT(*) AS `count`, SUM(price) AS `price` FROM `table3`

当我运行此查询时,我得到:

count   price
19      5609399
8       946000
4       0

当在PHP中循环时,这反过来不起作用,因为它们是3个单独的值,我只返回“count = 19 and price = 5609399”。它们并非全部以countprice的形式汇总在一起。

非常感谢任何帮助:)

3 个答案:

答案 0 :(得分:4)

SELECT COUNT(*) AS `count`, SUM(price) AS `price`
FROM
(
SELECT price from `table1` UNION ALL
SELECT price FROM `table2` UNION ALL
SELECT price FROM `table3`
) X

或通常组合3对值

select sum(`count`) `count`, sum(`price`) `price`
FROM
(
SELECT COUNT(*) AS `count`, SUM(price) AS `price` FROM `table1` UNION ALL
SELECT COUNT(*) AS `count`, SUM(price) AS `price` FROM `table2` UNION ALL
SELECT COUNT(*) AS `count`, SUM(price) AS `price` FROM `table3`
) X

一般,在组合表时使用UNION ALL,而不是UNION,因为UNION删除了重复项,所以如果你的计数/总和是

1, 100
1, 100
2, 200

联合查询导致

1, 100    # duplicate collapsed
2, 200

答案 1 :(得分:3)

你可以这样做:

SELECT count(1) AS `count`, SUM(price) AS `price`
FROM (SELECT price FROM `table1`
      UNION ALL
      SELECT price FROM `table2`
      UNION ALL
      SELECT price FROM `table3`) AS `t`

答案 2 :(得分:0)

尝试将此作为表格的模式 -

SELECT
  (SELECT COUNT(*) FROM table1) + (SELECT COUNT(*) FROM table2),
  (SELECT SUM(price) FROM table1) + (SELECT SUM(price) FROM table2);