【发布时间】:2020-04-27 18:13:05
【问题描述】:
我有两张桌子,
table1
=======================================
pid pname coldate col4
---------------------------------------
1 Tesitng Name1 2019-01-01 self
2 Tesitng Name2 2020-01-01 self
3 Tesitng Name3 2020-03-01 self2
4 Tesitng Name4 2020-04-04 self2
5 Tesitng Name5 2020-04-05 self3
table1 中的 pid 有唯一键
table2 //which have more than 600k rows
=======================================
billid rate pid
---------------------------------------
1 30 1
2 50 1
3 40 1
4 20 2
5 60 2
6 10 3
///在table2 billid中有唯一的key
我尝试显示 table1 的所有行以及 table2 的 rate 列的总和 where table1.pid=table2.pid
结果应该是这样的
table1
=======================================================
pid pname coldate col4 total
-------------------------------------------------------
1 Tesitng Name1 2019-01-01 self 120
2 Tesitng Name2 2020-01-01 self 80
我正在使用此查询,它对我有用,但需要很长时间,请告诉我最快的方法
SELECT t1.*,
(SELECT sum(rate) as total FROM table2 where pid=t1.pid) as total
FROM table1 t1 WHERE t1.coldate BETWEEN '2020-01-0' AND '2020-04-01'
AND t1.col4 Like 'self' ORDER BY t1.pid DESC;
我正在使用 php 和 mysql..
【问题讨论】:
标签: mysql sql group-by mysql-workbench query-optimization