Selecting MYSQL column conditionally

前端 未结 3 1926
天涯浪人
天涯浪人 2021-01-12 06:14

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,
         


        
相关标签:
3条回答
  • This ought to give you what you're looking for:

    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;
    
    0 讨论(0)
  • 2021-01-12 06:59

    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;
    
    0 讨论(0)
  • 2021-01-12 07:07
    select player1id from players where player2id=1
    union
    select player2id from players where player1id=1
    

    SQL FIDDLE DEMO

    0 讨论(0)
提交回复
热议问题