1

I am trying to do an IF function in MySQL that i thought would be pretty straightforward, but seems to be a little for complex.

Here's the idea:

SELECT IF(score1>score2, (name1,score1,name2,score2),(name2,score2,name1,score1)) AS (winner,w_score,loser,l_score) FROM game table

what I am trying to do is test score1 > score2, depending on the result, order the fields I want.

3
  • 1
    I'm not sure you can reorder the fields in your select using IF. You should probably do that outside of the query, like in PHP (or whatever language you're using). Commented Nov 14, 2013 at 3:11
  • the first three below all work great. Thanks. Commented Nov 14, 2013 at 17:28
  • You can use nested IF statements like this: janac.medium.com/… Commented Dec 3, 2020 at 18:27

3 Answers 3

1

Considering if score1 ,score2 ,name1 ,name2 are the column names in your game table , you could do like this :

SELECT
     IF( score1 > score2 ,name1 ,name2 ) AS winner
    ,GREATEST( score1 ,score2 ) AS w_score
    ,IF( score1 > score2 ,name2 ,name1 ) AS loser
    ,LEAST( score1 ,score2 ) AS l_score
FROM
    game
Sign up to request clarification or add additional context in comments.

1 Comment

Neat. Never seen the GREATEST and LEAST functions before :)
0

It looks like what you need is four different IF statements:

SELECT 
    IF(score1 > score2, name1, name2) AS winner,
    IF(score1 > score2, score1, score2) AS w_score,
    IF(score1 > score2, name2, name1) AS loser,
    IF(score1 > score2, score2, score1) AS l_score
FROM game_table

It's not the prettiest thing, but as the comparison is pretty straightforward, it should behave fine.

Comments

0

I offer a simple solution:

SELECT name1 AS winner, score1 AS w_score, name2 AS looser, score2 AS l_score
FROM game table WHERE score1 > score2
UNION
SELECT name2 AS winner, score2 AS w_score, name1 AS looser, score1 AS l_score
FROM game table WHERE score2 > score1

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.