高级MySQL IF函数

高级MySQL IF函数,mysql,if-statement,Mysql,If Statement,我正在尝试在MySQL中实现一个IF函数,我认为它非常简单,但似乎有点复杂 我的想法是: 选择IF(score1>score2,(name1,score1,name2,score2),(name2,score2,name1,score1)) AS(赢家、w_分数、输家、l_分数) 从游戏桌 我试图做的是测试score1>score2,根据结果,对我想要的字段进行排序。我提供了一个简单的解决方案: SELECT name1 AS winner, score1 AS w_score, name2 A

我正在尝试在MySQL中实现一个IF函数,我认为它非常简单,但似乎有点复杂

我的想法是:

选择IF(score1>score2,(name1,score1,name2,score2),(name2,score2,name1,score1))
AS(赢家、w_分数、输家、l_分数)
从游戏桌


我试图做的是测试score1>score2,根据结果,对我想要的字段进行排序。

我提供了一个简单的解决方案:

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

我提供了一个简单的解决方案:

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

看起来您需要的是四种不同的IF语句:

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

这不是最漂亮的东西,但由于比较非常简单,它应该表现得很好。

看起来您需要的是四种不同的IF语句:

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

这不是最漂亮的东西,但由于比较非常简单,它应该表现得很好。

考虑到
score1
score2
name1
name2
游戏
表中的列名,您可以这样做:

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

考虑到
score1
score2
name1
name2
game
表中的列名,您可以这样做:

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

我不确定您是否可以使用
IF
对select中的字段重新排序。您可能应该在查询之外这样做,比如在PHP(或您正在使用的任何语言)中。谢谢。您可以像这样使用嵌套的IF语句:我不确定您是否可以使用
IF
对select中的字段重新排序。您可能应该在查询之外这样做,比如在PHP(或您正在使用的任何语言)中。谢谢。你可以使用嵌套的IF语句,比如:Neat。以前从未见过
最大的
最小的
函数:)整洁。以前从未见过
最大值
最小值
函数:)