我max在where子句中有一个带有 a 的查询,这很慢。
select count(*)
from TableName tbl1
where tbl1.id = (
select max(tbl2.id)
from TableName tbl2
where tbl2.companyId = tbl1.companyId)
and tbl1.active = 2
Run Code Online (Sandbox Code Playgroud)
请注意,两个表是相同的。
我把它改写为:
select count(*)
from TableName tbl1
inner join (
select max(id) as id, companyId
from TableName tbl2
where tbl2.active= 2
group by companyId
) tbl2
on tbl2.companyId = tbl1.companyId
and tbl2.id=tbl1.id
Run Code Online (Sandbox Code Playgroud)
但记录数不同。
谁能说我如何重写它以获得更好的性能?