我知道这个问题与这个问题非常相似: Symmetric cross join 而且这个也是: combinations (not permutations) from cross join in sql
但是,如果我们有两个不同的表,比如说A和B:
select A.id,B.id from A cross join B
我想将(a,b)
对等(b,a)
?
答案 0 :(得分:14)
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 :(得分:1)
这也不能给出理想的结果吗?
select A.id,B.id from A cross join B on A.id >= B.id