簡體   English   中英

PostgreSQL按不同表中的多列排序

[英]Postgresql Order by multiple columns from different tables

我有以下表格:

資料來源:

**id  | name**

 1      source1

 2      source2

 3      source3

 4      source4

項目:

**id | name | sourceId | created_at**

1    item3      3      2018-08-09 07:28:17

2    item2      2      2018-08-09 07:30:00

的SQL:

SELECT
    sources.id,
    sources.name
FROM
     sources
LEFT JOIN
     items
         ON items.sourceId = sources.id
ORDER BY items.created_at DESC, sources.id

期望:

**id  | name**

2      source2

3      source3

1      source1

4      source4

說明:

我需要一個結果,其中包含源表中的所有源,但按最近使用過的源(分配給項的源)排序。以某種方式,第一個結果是源表中的結果,然后按desc順序在中找到項目表,如下所示:

實際結果:

**id  | name**

1      source1 

4      source4

2      source2

3      source3

我設法通過第二個sql獲得了預期的結果,但我認為我的第一次嘗試也有解決方案:

(SELECT
    sources.id,
    sources.name
FROM
     sources
INNER JOIN
     items
         ON items.sourceId = sources.id
ORDER BY items.created_at DESC, sources.id)
UNION ALL
(SELECT
       sources.id,
       sources.name
FROM
     sources
LEFT JOIN
    items
ON items.sourceId = sources.id
WHERE items.sourceId IS NULL)

上面的sql的另一個問題是,我不太了解為什么在使用UNION時訂單混亂,但是在使用UNION ALL時訂單正確。 據我所知,唯一的區別是UNION消除了重復項,而UNION ALL卻沒有

如果我做對了, NULLS LAST可能會解決問題。

...
ORDER BY items.created_at DESC
                          NULLS LAST,
         sources.id;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM