Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting MYSQL column conditionally

Example schema for my question is given at SQLFiddle and as follow:

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);

In a online game, I want to select opponent, which could be in player player1id or player2id.

Example Input/ output needed

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

That is, required data could be in any column but I need output in single column conditionally or any other way. I heard about MySQL conditional column but could not create query to get required output. Can someone please help with required query.

Edit

Based on this link, I run following query but failed.

SELECT IF(PLAYER1ID IS 1,PLAYER2ID as opponent,PLAYER1ID as opponent) 
FROM players
WHERE PLAYER1ID = 1 OR PLAYER2ID = 1;
like image 677
Kapil Sharma Avatar asked Nov 05 '12 05:11

Kapil Sharma


2 Answers

I think you may use case when then syntax as below:

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

Alternatively:

SELECT CASE WHEN player1id = 1 THEN player2id WHEN player2id =1 THEN player1id  END
FROM players WHERE player1id =1 OR player2id=1;
like image 68
Yogendra Singh Avatar answered Sep 28 '22 06:09

Yogendra Singh


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

SQL FIDDLE DEMO

like image 33
AnandPhadke Avatar answered Sep 28 '22 06:09

AnandPhadke