【发布时间】:2020-08-11 11:52:10
【问题描述】:
我有两张桌子,
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 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 0
我正在使用这个查询
SELECT
t1.*
, ttl.total
FROM table1 t1
inner join
(SELECT pid, sum(rate) as total
FROM table2
GROUP BY pid) as ttl
on ttl.pid=t1.pid
WHERE
t1.coldate BETWEEN '2020-01-01' AND '2020-04-01'
AND t1.col4 = 'self'
ORDER BY t1.pid DESC;
但它不显示表 1 中哪个 pid 不在表 2 中的行 请告诉我执行此操作的最快方法 我正在使用 php 和 mysql..
【问题讨论】:
-
“它不显示 table1 行,其中 pid 不在 table2 中”。你不问那个。你怎么期望得到那个???
-
如果你想要table1中的行,而pid不在table2中,
ttl.total有什么意义?它将永远是NULL。