【问题标题】:Match function for integer in mysqlmysql中整数的匹配函数
【发布时间】:2016-12-04 00:55:05
【问题描述】:

我有一个表结构

 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”、“col_4”等列查找“max”列值得出的。它应该返回我的索引或列号,从 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;

【问题讨论】:

    标签: mysql sql indexing match rank


    【解决方案1】:

    这是一种蛮力的方法:

    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;
    

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

    我还应该注意,您可以使用 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;
    

    这在计算上大致相同,但长度肯定要短得多。

    【讨论】:

      猜你喜欢
      • 2016-06-11
      • 2015-04-20
      • 2021-10-22
      • 2020-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      相关资源
      最近更新 更多