tbl_orders
order_id, qty
123, 2
124, 1
125, 3
126, 1
127, 1
128, 1
129, 4
tbl_score
order_id, name, created
123, product 1, 2018-06-01
124, product 1, 2018-06-01
125, product 1, 2018-06-02
126, product 3, 2018-06-02
127, product 2, 2018-06-03
128, product 3, 2018-06-03
129, product 3, 2018-06-03
必填输出
2018-06-01 2018-06-02 2018-06-03
product 1 3 3 0
product 2 0 0 1
product 3 0 1 5
以下查询将生成2018-06-01所需的输出,但是大约需要1分45秒才能在实时数据库上完成。如果我使用case
添加更多日期,则会花费更多时间。有人可以帮助我进行微调还是建议其他解决方案?
select s.name,
sum( case when date(s.created) = '2018-06-01' then o.qty else 0 end ) as 'June 1'
from tbl_score s inner join tbl_order o
on s.order_id=o.order_id group by s.name;