优化 SQL 语句

Optimizing SQL statement

我正在尝试 运行 一个 sql 查询,该查询在 mysql 上花费了很多时间。 table 非常大(超过 160000 行)。我有以下 table 结构

id | clientID | type | price | code | created_at

期望的输出是:

ldate | Cid | Total | Total2

我目前正在使用这个查询:

select max(created_at) as ldate, clientID as Cid, 
  (SELECT SUM(price) as total from invoice 
   where clientID = Cid and type = 9  and code <> 0) as total,
  (SELECT SUM(price) as total from invoice 
   where clientID = Cid and type = 9 ) as total2 
from invoice 
group by clientID 
having max(created_at) < '2019-09-01'

有没有办法优化此查询以运行更快,或者问题是否只与大量行有关。

有什么建议吗?

如果我正确理解了您的查询意图,您可以使用条件聚合而不是标量子查询,因此 table 仅被扫描一次:

select 
    max(created_at) as ldate, 
    clientid as cid, 
    sum(case when type = 9 and code <> 0 then price else 0 end) as total,
    sum(case when type = 9 then price else 0 end) as total2
from invoice 
group by clientid 
having max(created_at) < '2019-09-01'