mysql 中整数的匹配函数

Match function for integer in mysql

我有一个table结构

 ID   Col_1   col_2  col_3  col_4  max
    1    34     23     45     32   45
    2    20     19     67     18   67 
    3    40     10     76     86   86

我想得出这样的结果,排名列是根据 "col_1"、"col_2"、"col_3" 等列查找 "max" 列值得出的"col_4"。它应该 return 我的索引或列号从 col_1 的 1 开始,col_2 的 2 等等

ID   Col_1   col_2  col_3  col_4  max  rank
    1    34     23     45     32   45    3
    2    20     19     67     18   67    3
    3    40     10     76     86   86    4

这是我尝试过但无法获得所需输出的方法。 任何帮助将不胜感激。

 SELECT ID,Col_1,col_2,col_3,col_4,max, match(max) AGAINST(col_1,col_2,col_3,col_4) from demo;

这是一种比较暴力的方法:

select d.*,
       (case greatest(col_1, col_2, col_3, col_4, col_5)
            when col_1 then 1
            when col_2 then 2
            when col_3 then 3
            when col_4 then 4
            when col_5 then 5
        end) as max_index
from demo d;

注意:需要进行此类操作表明数据模型存在缺陷。列值可能应该存储在一个 table 中,每行有一个这样的值。

我还应该注意,您可以使用 field():

select d.*,
       field(greatest(col_1, col_2, col_3, col_4, col_5), 
             col_1, col_2, col_3, col_4, col_5)
from demo d;

这在计算上的工作量大致相同,但长度肯定短得多。