Can you add an if statement in ORDER BY?

后端 未结 2 1685
天涯浪人
天涯浪人 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:03

    Use the CASE statement.

    Example from http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html:

    SELECT id, first_name, last_name, birthday
    FROM table
    ORDER BY
    -- numeric columns
    CASE _orderby WHEN 'id' THEN id END ASC,
    CASE _orderby WHEN 'desc_ id' THEN id END DESC,
    -- string columns
    CASE _orderby WHEN 'first_name' THEN first_name WHEN 'last_name' THEN last_name END ASC,
    CASE _orderby WHEN 'desc_first_name' THEN first_name WHEN 'desc_last_name' THEN last_name END DESC,
    -- datetime columns
    CASE _orderby WHEN 'birthday' THEN birthday END ASC,
    CASE _orderby WHEN 'desc_ birthday' THEN birthday END DESC;
    

提交回复
热议问题