我有两个表ab,其中b包含表fk_a_id id列的外键a

现在,我想在表a上进行选择,但是根据表b是否具有外键条目来对结果进行排序。表b没有条目的行应排在第一位。

除了加入之外,我还没有尝试太多,这甚至可能不是正确的方向。

select a.*
from a as a
join b as b on b.fk_a_id = a.id
order by id desc

最佳答案

一种方法是left join。但是,如果b包含给定键的多个实例,则可能会重复行。

另一种方法在order by中使用逻辑:

select a.*
from a
order by (case when not exists (select 1 from b where b.fk_a_id = a.id) then 1 else 2 end),
          id desc;


为了提高性能,您需要在b(fk_a_id)上建立索引。

07-26 09:27
查看更多