繁体   English   中英

使用带回退的右表订购左外部联接

[英]Ordering left outer join using right table with fallback

我有两个桌子:

  • 表1-ID,created_at
  • Table2,Id,table1_id,created_at

我想通过获取最新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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM