根据特定值 postresql 对记录进行排序

时间:2021-02-23 09:07:34

标签: ruby-on-rails postgresql sql-order-by

我有三张桌子 1)fruits -- id, name 2)国家——身份证,姓名 3)fruit_countries -- id,fruit_id(fk), country_id(fk)

在我的水果表中,我想在顶部显示特定国家/地区不存在的水果。

我用过

select
    distinct(fruits.*),case when fruit_countries.country_id = xx then 1 else 0 end
from
    "fruits"
left join fruit_countries on
    fruit_countries.fruit_id = fruits.id
order by case when fruit_countries.country_id = xx then 1 else 0 end

问题是,由于一种水果可以与多个国家/地区相关联,因此当它们出现在 xx 国家和其他一些国家/地区时,列表中的水果记录很少。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

demo:db<>fiddle

SELECT
    *
FROM fruits f
LEFT JOIN fruit_countries fc ON f.id = fc.fruit_id
ORDER BY bool_or(fc.country_id = 1) OVER (PARTITION BY fc.fruit_id)

您可以在 bool_or() 子句中使用 ORDER BY 窗口函数。这将检查每个 fruit_id 组(分区)是否有任何记录与请求的 country_id。如果没有,将首先订购。

但是,正常的 ORDER BYNULL 记录排序到底部。但是,显然它们也没有分配给特定的 country_id(它们是 NULL,因为没有分配给任何国家/地区),您可以将 NULLS FIRST 添加到 ORDER BY 子句, 每次都将这些水果放在上面。

答案 1 :(得分:0)

如果您使用的是 rails 6.1,则可以使用

Fruit.where.missing(:countries) + Fruit.includes(:countries)
相关问题