用SQL生成對戰表

前幾天發生在羣裏的討論
下面有如下需求
c1 球隊ID
c2 球隊名稱
SQL> with dao as
2  (
3    select 1 c1,’a’ c2 from dual
4    union all
5     select 2 c1,’b’ c2 from dual
6     union all
7      select 3 c1,’c’ c2 from dual
8  )
9  select *
10  from dao
11  /C1 C
———- -
1 a
2 b
3 c

現在需要生成一張對戰表
每個球隊都要與其他球隊對戰一次。
解法1:簡單不等連接

SQL> with dao as
2  (
3    select 1 c1,’a’ c2 from dual
4    union all
5     select 2 c1,’b’ c2 from dual
6     union all
7      select 3 c1,’c’ c2 from dual
8  )
9  select t1.c2||’ PK ‘||t2.c2
10  from dao t1,dao t2
11  where t1.c1 <t2.c1
12  /

T1.C2|
——
a PK b
a PK c
b PK c
解法2:分析函數
SQL> with dao as
2  (
3    select 1 c1,’a’ c2 from dual
4    union all
5     select 2 c1,’b’ c2 from dual
6     union all
7      select 3 c1,’c’ c2 from dual
8  )
9  select res
10  from
11  (
12  select row_number() over ( order by t1.c1+t1.c1) rn ,t1.c2||’ PK ‘||t2.c2 res
13  from dao t1,dao t2
14  where t1.c2 !=t2.c2 ) inner
15  where mod(inner.rn,2) =1
16  /RES
——
a PK b
b PK a
c PK a

解法3:遞歸查詢
SQL> with dao as
2  (
select 1 c1,’a’ c2 from dual
3    4    union all
5     select 2 c1,’b’ c2 from dual
6     union all
7      select 3 c1,’c’ c2 from dual
8  )
9  select cola||’ PK ‘||colb
10  from (
11  select prior c2 cola,c2 colb
12  from dao
13  connect by prior c1=c1+1)
14  where cola is not null
15  ;COLA||
——
b PK a
c PK b
b PK a

從實現方法上來看第一種是最好的方式,簡單,高效。
我們寫程序不一定非得要用某些複雜的特性,
只要能滿足需求,越簡單的,往往意味越高效。

發佈了91 篇原創文章 · 獲贊 8 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章