MySQL:如何为图像所代表的以下场景编写查询?

时间:2015-07-30 13:16:14

标签: mysql sql

enter image description here

我试过了,但我的查询加载了太多的数据来计算这个。 请建议我,如何为这种情况编写单个查询。

1 个答案:

答案 0 :(得分:1)

由于你已经在这里用mysql标记了这个问题,你怎么做呢

select
t1.id,
t1.user_name,
sum(case when t2.shop_status = 'returned' then 1 else 0 end)  as `num_of_return`,
sum(case when t2.shop_status = 'shopped' then 1 else 0 end)  as `num_of_shopped`,
sum(case when t2.shop_status = 'cancelled' then 1 else 0 end)  as `num_of_cancelled`
from table1 t1
left join table2 t2 on t2.user_id = t1.id
group by t1.id