9

SQLFiddle给出了我的问题的示例架构,如下所示:

CREATE TABLE `players` (
  `player1id` int(11) NOT NULL,
  `player2id` int(11) NOT NULL,
  PRIMARY KEY (`player1id`,`player2id`)
) ENGINE=InnoDB;

INSERT INTO `players` values
(1,5),
(1,7),
(5,3),
(5,4),
(2,1);

在在线游戏中,我想选择对手,可以在玩家player1idplayer2id.

示例 需要输入/输出

Input 1: Output 5, 7, 2
Input 5: Output 1, 3 ,4
& so on.

也就是说,所需的数据可以在任何列中,但我需要有条件或以任何其他方式在单列中输出。我听说过 MySQL 条件列,但无法创建查询来获取所需的输出。有人可以帮助解决所需的查询。

编辑

基于此链接,我运行以下查询但失败。

SELECT IF(PLAYER1ID IS 1,PLAYER2ID as opponent,PLAYER1ID as opponent) 
FROM players
WHERE PLAYER1ID = 1 OR PLAYER2ID = 1;
4

3 回答 3

15

我认为您可以使用case when then如下语法:

SELECT CASE WHEN player1id = 1 THEN player2id ELSE player1id  END
FROM players WHERE player1id =1 OR player2id=1;

或者:

SELECT CASE WHEN player1id = 1 THEN player2id WHEN player2id =1 THEN player1id  END
FROM players WHERE player1id =1 OR player2id=1;
于 2012-11-05T05:51:22.143 回答
3
select player1id from players where player2id=1
union
select player2id from players where player1id=1

SQL 小提琴演示

于 2012-11-05T05:46:10.603 回答
2

这应该给你你正在寻找的东西:

SET @PlayerId = 1;
SELECT `player2id` AS 'Other Player ID'
  FROM `players`
 WHERE `player1id` = @PlayerId
   AND `player2id` != @PlayerId

 UNION
 SELECT `player1id`
  FROM `players`
 WHERE `player2id` = @PlayerId
   AND `player1id` != @PlayerId;


SET @PlayerId = 5;
SELECT `player2id` AS 'Other Player ID'
  FROM `players`
 WHERE `player1id` = @PlayerId
   AND `player2id` != @PlayerId

 UNION
SELECT `player1id`
  FROM `players`
 WHERE `player2id` = @PlayerId
   AND `player1id` != @PlayerId;
于 2012-11-05T05:57:06.323 回答