mysql两张表一起计数_MySQL从第二个表中加入两个表计数和求和

如果我理解你的问题,你需要做的就是添加一个SUM():

SELECT a.*,

Count(b.id) as counttotal,

sum(b.costs) TotalCost

FROM dealers a

LEFT JOIN inquiries b on a.id=b.dealer_id

GROUP BY a.id

ORDER BY name ASC我的建议是使用子查询来获取count和sum:

SELECT a.*,

b.countTotal,

b.TotalCosts

FROM dealers a

LEFT JOIN

(

select COUNT(ID) countTotal,

SUM(costs) TotalCosts,

dealer_id

from inquiries

group by dealer_id

) b

on a.id=b.dealer_id

ORDER BY name ASC我猜你从原始查询中使用的是MySQL。我建议使用子查询,因为MySQL使用GROUP BY的扩展,它允许选择列表中的项目是非聚合的,不包含在GROUP BY子句中。但是这会导致意外的结果,因为MySQL可以选择返回的值。 (见MySQL Extensions to GROUP BY)

来自MySQL Docs:

MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. ... You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate. Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause. Sorting of the result set occurs after values have been chosen, and ORDER BY does not affect which values the server chooses.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值