在同一张表中进行的数据库笛卡尔积

8

我有一个只有一列的三行表格,如下所示:

col1

team1
team2
team3
team4

我想要进行自连接操作,并得到以下结果:
team1, team2
team1, team3
team1, team4
team2, team3
team2, team4
team3, team4

2个回答

8

笛卡尔积在数据库中被称为交叉连接,您可以在where子句中删除球队相等的行:

select
    t1.col1, t2.col1
from teams as t1
    cross join teams as t2
where
    t1.col1 <> t2.col1

6
小修正:为了获得问题中指定的期望结果(组合而非排列),你需要使用where t1.col1 > t2.col1。否则,你将得到(1,1)以外的其他结果,而你只想要卡特esian积的一半组合。请注意不改变原文的意思。 - okdewit

1
你可以这样将两个表格连接起来以获得期望的输出结果:
select t1.col1, t2.col1
from table t1
join table t2
on t1.col1 <> t2.col1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接