我有两个表
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
数据6
和5
进行排序。这可能吗?
编辑:最终表需要按col1.date
和col2.date
排序,以便较早的日期(col1
或 col2
(将在联接表中排序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
SQL Fiddle
select col1, date1, col2, date2
from
t1
full outer join
t2 on col1 = col2
order by coalesce(date1, date2), date2;
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 与新数据
SQLFiddle with old data
值得庆幸的是,PostgeSQL有一个很棒的函数,叫做LEAST()
;查询很简单:
SELECT col1, date1, col2, date2
FROM t1
FULL OUTER JOIN t2
ON col1 = col2
ORDER BY LEAST(date1, date2), GREATEST(date1, date2)
(数据集 1 的小提琴,数据集 2 的小提琴(。
<小时 />编辑
添加了对GREATEST()
的使用,然后按其他值进行排序。