Can you add an if statement in ORDER BY?

后端 未结 2 1687
天涯浪人
天涯浪人 2020-11-27 04:24

I am trying to achieve the following:

I have a single ORDER BY statement which could vary depending on the value stored in Column A.

For example:

if

2条回答
  •  没有蜡笔的小新
    2020-11-27 05:08

    Well, you can use the IF function in MySQL (Note the emphasis on function since there's also an unrelated IF statement)...:

    ORDER BY IF(TYPE='Member', LNAME, GROUPNAME) ASC
    

    However, in this case it seems the better choice (From a flexibility standpoint) would be the CASE statement:

    ORDER BY 
        CASE `type` 
            WHEN 'Member' THEN LNAME 
            WHEN 'Group' THEN GROUPNAME
            ELSE 1 END 
        ASC
    

    Note that the entire block from CASE to END is to be considered as a single "unit". The result of which is what you're trying to sort against (Hence why the ASC comes after the block, rather than inside of it)...

提交回复
热议问题