2012-10-17 75 views

回答

11
select A.id aid,B.id bid 
from A inner join B on a.id <= b.id 
union 
select B.id,A.id 
from A inner join B on b.id < a.id 

如果你想成爲更復雜的:

select distinct 
     case when a.id<=b.id then a.id else b.id end id1, 
     case when a.id<=b.id then b.id else a.id end id2 
from A cross join B 

在我的小不科學的烘烤關與小表,後者爲快。在下面,case表達式被寫爲子查詢。

select distinct 
     (select MIN(id) from (select a.id union select b.id)[ ]) id1, 
     (select MAX(id) from (select a.id union select b.id)[ ]) id2 
from A cross join B 
+1

在其中一個條件中不應該存在一個「<=」嗎? – podiluska

+0

+1除了其中一個連接應包含'a = b',即'a.id <= b.id' – Bohemian

+0

@podiluska好抓! – RichardTheKiwi