Postgresql 按不同表中的多列排序

Postgresql Order by multiple columns from different tables

我有以下 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

解释:

我需要一个结果,其中包含来源 table 中的所有来源,但按最近使用的来源(分配给项目的来源)排序。不知何故,第一个结果是来自来源 table 的结果然后在 desc 顺序中可以在项目 table 中找到的那些,如下所示:

实际结果:

**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;