如何在3个不同的列中按最小值排序?

时间:2013-06-11 17:32:00

标签: mysql select multiple-columns

我的table_a:

A|B|C // Columns
3|4|0 // Values

我想先通过小值进行选择排序.. 像这样:

"SELECT * FROM table_a ORDER BY (smallest of A,B,C first, second and third (Bigger one)) ASC"

returns: C=0,A=3,B=4

这可能吗?不使用PHP或其他脚本?

1 个答案:

答案 0 :(得分:0)

这是一个快速而又肮脏的尝试,但似乎得到了理想的结果,但并不完全确定为什么你会想要这样做。 http://sqlfiddle.com/#!2/1d3ec/2

SELECT
    l2.A,
    l2.B,
    l2.C
FROM (
    SELECT
        l1.A,
        l1.B,
        l1.C,
        l1.smallestColumn,
        l1.largestColumn,
        CASE
            WHEN l1.A > l1.smallestColumn AND l1.A < l1.largestColumn THEN l1.A
            WHEN l1.B > l1.smallestColumn AND l1.B < l1.largestColumn THEN l1.B
            ELSE l1.C -- Fallback to C, in case of a tied result
        END AS middleColumn
    FROM (
        SELECT
            A,
            B,
            C,
            LEAST( A , B , C ) AS smallestColumn,
            GREATEST( A , B , C ) AS largestColumn
        FROM table_a
    ) l1
) l2
ORDER BY
    l2.smallestColumn,
    l2.middleColumn,
    l2.largestColumn;