MySQL greatest value in row?

前端 未结 6 1834
日久生厌
日久生厌 2021-01-07 13:31

I\'m using MySQL with PHP. This is like my table: (I\'m using 3 values, but there are more)

id | 1 | 2 | 3
---+---+---+----
1  | 3 |12 |-29
2  | 5 |8  |8
3  | 99|7         


        
6条回答
  •  抹茶落季
    2021-01-07 13:50

    This query will return the max value regardless of NULLs

    SELECT MAX(value)
    FROM
    (SELECT 1 column_no, col1 value
    FROM anotherunamedtable
    UNION ALL
    SELECT 2, col2
    FROM anotherunamedtable
    UNION ALL
    SELECT 3, col3
    FROM anotherunamedtable) t
    

    If you really need the column number then

    SELECT id,
           (SELECT column_no
           FROM
                  (SELECT 1 column_no, col1 value
                  FROM anotherunamedtable
                  WHERE id = t.id
                  UNION ALL
                  SELECT 2, col2
                  FROM anotherunamedtable
                  WHERE id = t.id
                  UNION ALL
                  SELECT 3, col3
                  FROM anotherunamedtable
                  WHERE id = t.id) s
            ORDER BY max_value DESC
            LIMIT 1)) as column_no
    FROM anotherunamedtable t
    

    But I think that the last query might perform exceptionally horrible. (Queries are untested)

提交回复
热议问题