您可以将where
条件移动到from
子句中,您可以在其中left outer join
。一种方法是将条件放在on
子句中:
SELECT PRH.prid, PRH.CreationDate, PRH.ClosedDate, PRA.creationdate
FROM PRHeader PRH left join
PRAction PRA
on PRH.PrId = PRA.PrId and
PRA.CreationDate = (select min(CreationDate)
from PRAction pa
WHERE PRH.prid = pa.prid and pa.ActionTypeId<>4
);
另一种方法是将其作为join
条件:
select PRH.prid, PRH.CreationDate, PRH.ClosedDate, pa.creationdate
from PRHeader PRH left join
(select prid, min(CreationDate)
from PRAction pa
where pra.ActionTypeId <> 4
group by prid
) pa
on PRH.prid = pa.prid;
最后,如果您不想进行聚合,可以将字段计算移至select
子句:
select PRH.prid, PRH.CreationDate, PRH.ClosedDate,
(select min(CreationDate)
from PRAction pa
where PRH.prid = pa.prid and pa.ActionTypeId <> 4
) as CreationDate
from PRHeader PRH;
虽然这看起来像一个聚合,但引擎应该能够PRAction(prid, CreationDate)
直接使用索引。您可以通过创建子查询使这一点更明显(使用 MySQL 语法):
(select CreationDate
from PRAction pa
where PRH.prid = pa.prid and pa.ActionTypeId <> 4
order by CreationDate
limit 1
) as CreationDate