SQL从多个列中选择最接近的值并按最佳顺序排序

时间:2019-03-21 23:39:12

标签: mysql sql

我的表有8列,可以说: 我的表格名称是x_table,其列为:id,score_1,score_2,score_3,score_4,score_5,score_6,score_7 ..

每个score_ *列的得分都在0到10之间。然后,我想用以下值搜索我的表:

得分_1 = 7,得分_2 = 9,得分_3 = 6,得分_4 = 9,得分_5 = 10,得分_6 = 8,得分_7 = 4。

如何选择此表并根据最接近的值显示结果

下面的查询无法提供我所需的100%:

SELECT *
FROM xc_t
WHERE t_id <> 0
    AND t_category1 BETWEEN 0
        AND 11
    AND t_category2 BETWEEN 0
        AND 11
    AND t_category3 BETWEEN 0
        AND 11
    AND t_category4 BETWEEN 0
        AND 11
    AND t_category5 BETWEEN 0
        AND 11
    AND t_category6 BETWEEN 0
        AND 11
    AND t_category7 BETWEEN 0
        AND 11
ORDER BY abs(t_category1 - 6)
    ,abs(t_category2 - 6)
    ,abs(t_category3 - 9)
    ,abs(t_category4 - 2)
    ,abs(tea_category5 - 9)
    ,abs(t_category6 - 4)
    ,abs(t_category7 - 10) limit 0
    ,20

1 个答案:

答案 0 :(得分:1)

我认为您想要greatest()

select t.*, greatest(score_1, score_2, . . ., score_8) as max_score
from t
order by max_score desc;

这是您想要的吗?

select t.*
from t
order by (abs(score_1 - @score_1) +
          abs(score_2 - @score_2) +
          . . .
          abs(score_7 - @score_7)
         )