【问题标题】:Sort full join based on two columns on two different tables根据两个不同表上的两列对完全连接进行排序
【发布时间】:2021-02-16 20:02:25
【问题描述】:

我的 PostgreSQL 数据库中有两个表(表 A 和表 B)。这两个表都有一个 createdAt 列。我想对这两个表进行完全连接,然后根据 A 和 B 表上的 createdAt 值对结果进行排序。下面是我想成为查询结果的示例。

表 A colA joinColumnA createdAtA ----- ------------ --------- a1 1 2014 a2 2 2019 a3 3 2020 表 B colB, joinColumnB createdAtB --- ---------- ----------- b1 2 2013 b2 4 2015 b3 5 2016 结果 colA, joinColumnA createdAtA colB joinColumnB createdAtB ---- ----------- ----------- ---- ----------- --------- -- a3 3 2020 null null null a2 2 2019 b1 2 2013 空空空 b3 5 2016 空空空b2 4 2015 a1 1 2014 null null null

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    你可以ORDER BY GREATEST(createdAtA, createdAtB):

    SELECT *
    FROM tableA
    FULL JOIN tableB
      ON tableA."joinColumnA" = tableB."joinColumnB"
    ORDER BY GREATEST("createdAtA", "createdAtB") DESC;
    
    colA joinColumnA createdAtA colB joinColumnB createdAtB
    a3 3 2020
    a2 2 2019 b1 2 2013
    b3 5 2016
    b2 4 2015
    a1 1 2014

    View on DB Fiddle

    【讨论】:

      【解决方案2】:

      您可以尝试使用最大 createdAT 的联合来连接左连接中的列,并按 ifnull(createdAtA, createdAtB) 顺序连接两个表

          select colA, joinColumnA, createdAtA, null colB, null joinColumnB,  null createdAtB
          from (
              select joinColumn, max(createdAt)
              from (
                  select joinColumnA joinColumn, createdAtA createdAt
                  from tableA
                  select joinColumnB , createdAtB
                  from tableB
              ) t1
              group by joinColumn
          ) t2
          left join tableA ON tableA.joinColumnA = t2.joinColumn
          left join tableB ON tableB.joinColumnA = t2.joinColumn
          order by nullif(createdAtA, createdAtB)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-04
        • 1970-01-01
        • 2021-07-20
        • 1970-01-01
        • 2015-05-10
        相关资源
        最近更新 更多