SQL通过order加入

时间:2014-04-19 07:02:03

标签: sql postgresql join postgresql-9.1

我有两张表

table 1
col1 date
1    13/4/2014
2    15/4/2014
3    17/4/2014
5    19/4/2014

table 2
col1 date
1    13/4/2014
3    16/4/2014
6    18/4/2014

joining the two tables i should get

col1 date       col2 date
1    13/4/2014  1    13/4/2014
2    15/4/2014
3    17/4/2014  3    16/4/2014
                6    18/4/2014
5    19/4/2014

重要的是date列应该按照col数据65进行排序。 这可能吗?

编辑: 最终表格需要按col1.datecol2.date排序,以便在col1col2中的早期日期将在联接表18/4/2014中排序在19/4/2014之前,即使它们位于不同的列中。我希望我明白我的观点。 谢谢 编辑:

table 1
1, "2014-04-03" 
2, "2014-04-04"
3, "2014-04-11"
4, "2014-04-16"
5, "2014-04-04"
6, "2014-04-17"
7, "2014-04-17"

table 2
1, "2014-04-04"
2, "2014-04-11"
5, "2014-04-17"

编辑:加入后应该像

1 2014-04-03 
2 2014-04-04 
5 2014-04-04 1 2014-04-04
3 2014-04-11 2 2014-04-11
4 2014-04-16 
6 2014-04-17
7 2014-04-17 5 2014-04-17

3 个答案:

答案 0 :(得分:6)

SQL Fiddle

select col1, date1, col2, date2
from
    t1
    full outer join
    t2 on col1 = col2
order by coalesce(date1, date2), date2;

答案 1 :(得分:1)

select n.col1
     , n.date1
     , m.col2
     , m.date2
from t1 n 
full join t2 m on n.date1 = m.date2
              and n.col1 = (select max(col1) from t1 where date1 = m.date2 )  
              and n.col1 is not null
where n.date1 is not null or m.date2 is not null
order by coalesce(n.date1, m.date2)
       , coalesce(n.col1, m.col2)

SQLFiddle with new data

SQLFiddle with old data

答案 2 :(得分:1)

值得庆幸的是,PostgeSQL有一个很棒的函数叫LEAST();那么查询就是:

SELECT col1, date1, col2, date2
FROM t1
FULL OUTER JOIN t2
             ON col1 = col2
ORDER BY LEAST(date1, date2), GREATEST(date1, date2)

fiddle for dataset 1fiddle for dataset 2)。


EDITED

添加使用GREATEST()然后按其他值排序。