[英]Ordering left outer join using right table with fallback
我有兩個桌子:
我想通過獲取最新Table2記錄(如果有的話,可能沒有任何table2記錄)的聯接包括所有Table1行,並在Table2上使用created_at命令對結果進行排序。 如果沒有Table2記錄,我希望能夠使用Table1中的created_at對該記錄進行排序。
例:
Table 1 (id, created_at)
1, 100
2, 200
3, 300
4, 400
Table 2 (id, table1_id, created_at)
1, 1, 500
2, 1, 450
3, 2, 350
並且查詢將給出結果(t1.id,t1.created_at,t2.id,t2.created_at)
1, 100, 1, 500
4, 400, --, --
2, 200, 2, 350
3, 300, --, --
我正在使用Postgresql。 什么是最好的查詢/方法來做到這一點?
select t1.id, t1.created_at, t2.id, t2.created_at
from
table1 t1
left outer join (
select id, max(created_at) created_at
from table2
group by id
) t2 on t1.id = t2.id
order by coalesce(f2.created_at, f1.created_at) desc;
想想我提出了一個看起來可行的查詢:
SELECT * FROM table1 AS t1
LEFT OUTER JOIN table2 AS t2 ON (
t2.t1_id = t1.id
AND
t2.id = (SELECT tt2.id FROM table2 tt2 WHERE tt2.t1_id = t1.id ORDER BY created_at DESC LIMIT 1)
) ORDER BY COALESCE(f2.created_at, f1.created_at) DESC;
不知道這是最好還是最有效的方法,因此我仍然願意提出建議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.