假设表一的数据是这样的,表二的数据是
这样的,现在要查询表一中所有人的消费总金额,也就是表二的price字段,并且status不等于0和5。
我自己写的查询语句是:
select d.* ,sum(o.price) money from user d left join order o on o.anbiz_id=d.anbiz_id where o.status not in(0,5) group by d.anbiz_id
这样只能查询到有产生订单的用户,如果没有订单的就查询不到,请问要怎么优化这个sql语句,变成,没有产生订单的用户,也能查询到信息,只不过消费总金额那边为0
select u.anbiz_id, ifnull(o.money, 0) moeny
from user u left join
(select anbiz_id, sum(price) money from order where status not in (0,5) group by anbiz_id) o on u.anbiz_id = o.anbiz_id;
大概就这意思,先聚合order表的用户消费数据,再用user表left join聚合后的数据
select d.* ,sum(ifnull(o.price,0)) money from user d left join order o on o.anbiz_id=d.anbiz_id where o.status not in(0,5) group by d.anbiz_id