gpt4 book ai didi

php - mySQL 选择计数,多个表

转载 作者:行者123 更新时间:2023-11-29 01:18:42 24 4
gpt4 key购买 nike

我有三个表:

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 的形式加在一起。

非常感谢任何帮助:)

最佳答案

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

关于php - mySQL 选择计数,多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5577215/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com