MYSQL:如何对数字DESC加上正高的值进行排序

时间:2019-04-25 07:50:02

标签: mysql

我需要一些帮助,以使用纯MYSQL创建所需的输出。我的问题是下面的By fire SQL:

SELECT
    r.questions_id
    ,r.Empty_Peg_Count AS 'Empty_Pegs'
FROM
    Training_Core.results AS r
ORDER BY
    CAST(r.Empty_Peg_Count AS SIGNED INTEGER) DESC;

我得到的输出如下:

Array
(
    [0] => Array
        (
            [questions_id] => 256332653
            [Empty_Pegs] => 2
        )

    [1] => Array
        (
            [questions_id] => 256332653
            [Empty_Pegs] => 2+
        )

    [2] => Array
        (
            [questions_id] => 256332653
            [Empty_Pegs] => 1
        )
)

我希望具有 + 符号的值具有较高的优先级,它应该首先显示。我想要的输出如下:

Array
(
    [0] => Array
        (
            [questions_id] => 256332653
            [Empty_Pegs] => 2+
        )

    [1] => Array
        (
            [questions_id] => 256332653
            [Empty_Pegs] => 2
        )

    [2] => Array
        (
            [questions_id] => 256332653
            [Empty_Pegs] => 1
        )
)

有人可以帮助我如何通过SQL查询获得此结果吗?

感谢前进!

3 个答案:

答案 0 :(得分:1)

您可以使用第二条order by规则:

ORDER BY
    CAST(r.Empty_Peg_Count AS SIGNED INTEGER) DESC
    ,r.Empty_Peg_Count LIKE '%+%' DESC;

这会将带有+的条目推到顶部。

答案 1 :(得分:1)

您可以使用RIGHT来检查最后一个字符是否为+并将其用作辅助ORDER BY字段:

SELECT
    r.questions_id
    ,r.Empty_Peg_Count AS 'Empty_Pegs'
FROM
    Training_Core.results AS r
ORDER BY
    CAST(r.Empty_Peg_Count AS SIGNED INTEGER) DESC
  , RIGHT(r.Empty_Peg_Count, 1) = '+' DESC

答案 2 :(得分:0)

您可以使用以下内容进行排序

SELECT * FROM `data` ORDER BY
CASE 
   WHEN right(`Empty_Pegs`,1) = '+' THEN (left(`Empty_Pegs`,1)*10)
ELSE `Empty_Pegs`
END DESC;