我正在尝试运行SQL查询以显示竞赛中一组战斗的结果。 战斗细节存储在战斗机1,战斗机2和胜利者的领域。 我需要做的就是把所有战斗的列表放在一起,每个战斗在列表中出现两次 - 例如,一次用
Competitor:fighter1, Opponent:fighter2, Winner:fighter1
以及列表中的其他地方
Competitor:fighter2, Opponent:fighter1, Winner:fighter1
我一直在使用sql union来从每次战斗中提取两次细节,并尝试为fighter1和fighter2列分配不同的别名来交换它们,但我甚至不确定这是否可能。< / p>
我的查询是这样的(省略了其他表中的不必要的东西)
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
有没有人知道如何交换这两个并且每次都被指定为“竞争对手”的战斗机订购列表?
提前致谢。
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分:0)
我认为UNION
会忽略不匹配的列名称,并根据列在两个SELECT
语句中的显示顺序对列进行排序。
因此,只需在第二个.fighter1
中交换.fighter2
和SELECT
。
答案 3 :(得分: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
答案 4 :(得分:0)
如果您的SQL产品支持它,请将UNION ALL
更改为UNION CORRESPONDING
。