有条件地选择MYSQL列

时间:2012-11-05 05:40:44

标签: mysql sql phpmyadmin

我的问题的示例模式在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条件列,但无法创建查询以获取所需的输出。有人可以帮助解决所需的查询。

修改

基于this link,我运行以下查询但失败了。

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

3 个答案:

答案 0 :(得分:6)

我认为您可以使用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;

答案 1 :(得分:3)

select player1id from players where player2id=1
union
select player2id from players where player1id=1

SQL FIDDLE DEMO

答案 2 :(得分: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;