2011-11-28 60 views
2

我試圖運行SQL查詢以在競爭中顯示一組打鬥的結果。 戰鬥細節存儲在戰鬥機1,戰鬥機2和獲勝者的字段中。 我需要做的就是把在一起的所有戰鬥的列表,每個戰鬥在列表中出現兩次 - 一次用,例如如果兩個'OR'條件都爲真,則返回相同的行

Competitor:fighter1, Opponent:fighter2, Winner:fighter1 

而且,其他地方的列表

Competitor:fighter2, Opponent:fighter1, Winner:fighter1 

我一直在使用一個sql union從每次打鬥拉兩次細節,並試圖給戰鬥機1和戰鬥機2列分配不同的別名來交換它們,但我甚至不確定這是否可能。

我的查詢是這樣的(與其他表省略不必要的東西)

SELECT wp_ema_fights.fighter1 AS competitor, 
wp_ema_fights.fighter2 AS opponent, 
wp_ema_fights.winner AS winner 
FROM wp_ema_fights 
UNION ALL 
SELECT wp_ema_fights.fighter1 AS opponent, 
wp_ema_fights.fighter2 AS competitor, 
wp_ema_fights.winner AS winner 
FROM wp_ema_fights 
ORDER BY competitor 

此查詢顯示各打了兩次,但像這樣:

Competitor:fighter1, Opponent:fighter2, Winner:fighter1 
Competitor:fighter1, Opponent:fighter2, Winner:fighter1 

有沒有人有任何想法如何我可以將兩者交換,並根據每次戰鬥機被指定爲「競爭對手」的順序排列列表。

在此先感謝。

回答

2

嘗試:

SELECT wp_ema_fights.fighter1 AS competitor, 
     wp_ema_fights.fighter2 AS opponent, 
     wp_ema_fights.winner AS winner 
FROM  wp_ema_fights 
UNION ALL 
SELECT wp_ema_fights.fighter2 AS competitor, 
     wp_ema_fights.fighter1 AS opponent, 
     wp_ema_fights.winner AS winner 
FROM  wp_ema_fights 
ORDER BY competitor 
+0

+1:不要移動SELECT語句中的字段,在***兩個*** SELECT語句中將它們保持相同的順序。 – MatBailie

+0

非常感謝!這正在做我現在需要的。 – user10403

0

我認爲UNION將忽略不匹配的列名,並根據它們在兩個SELECT語句中出現的順序排列列。

因此,只需在.fighter1.fighter2之間調換第二個SELECT即可。

0

嘗試:

SELECT wp_ema_fights.fighter1 AS competitor, 
wp_ema_fights.fighter2 AS opponent, 
wp_ema_fights.winner AS winner 
FROM wp_ema_fights 
UNION ALL 
SELECT wp_ema_fights.fighter2 AS competitor, 
wp_ema_fights.fighter1 AS opponent, 
wp_ema_fights.winner AS winner 
FROM wp_ema_fights 
ORDER BY competitor 
1

除了Xophmester的回答,您可以用連接而不是UNION的做到這一點。這具有僅加載源數據一次而不是兩次的優點。 (這是非常大的數據集,而不僅僅是小的更有意義。)

SELECT CASE WHEN Mode.ID = 1 THEN wp_ema_fights.fighter1 ELSE wp_ema_fights.fighter2 END AS competitor, 
     CASE WHEN Mode.ID = 2 THEN wp_ema_fights.fighter2 ELSE wp_ema_fights.fighter1 END AS opponent, 
     wp_ema_fights.winner AS winner 
FROM  wp_ema_fights 
CROSS JOIN (SELECT 1 as ID UNION ALL SELECT 2 as ID) AS Mode 
ORDER BY CASE WHEN Mode.ID = 1 THEN wp_ema_fights.fighter1 ELSE wp_ema_fights.fighter2 END 
0

如果你的SQL產品支持它,改變UNION ALLUNION CORRESPONDING

相關問題