mysql多表计数,MySQL选择计数,多个表

I have three tables:

table1, table2, table3

I am trying to get a total count of rows from each table as well as sum of price column, so for example:

$r['count'] = total rows of all 3 tables combined;

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

Here is my query:

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`

When I run this query, I am getting:

count price

19 5609399

8 946000

4 0

Which in turn does not work when looped out in PHP as they are 3 separate values and I am only being returned "count = 19 and price = 5609399". They don't all come out totaled together as count or price.

Any help is greatly appreciated :)

解决方案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

or generally to combine 3 pairs of values

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

Generally, use UNION ALL when combining tables, not UNION because UNION removed duplicates, so if your count/sum were exactly

1, 100

1, 100

2, 200

A union query results in

1, 100 # duplicate collapsed

2, 200

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值