【问题标题】:Select Statement that orders depending on existence of foreign key in other table选择根据其他表中是否存在外键进行排序的语句
【发布时间】:2018-01-22 01:54:35
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: sql sqlite


    【解决方案1】:

    一种方法是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) 上建立索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-15
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 2021-12-02
      • 2014-02-06
      相关资源
      最近更新 更多