简体   繁体   English

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

[英]SQL select closest values from multiple columns and order by the best

My table has 8 columns, let say: My table name is x_table and columns: id, score_1, score_2, score_3, score_4, score_5, score_6, score_7.. 我的表有8列,可以说:我的表名称是x_table,列是:id,score_1,score_2,score_3,score_4,score_5,score_6,score_7。

Each score_* columns has a score from 0 to 10. Then let say I want to search my table with the following values: 每个score_ *列的得分都在0到10之间。然后,我想用以下值搜索我的表:

score_1=7, score_2=9, score_3=6, score_4=9, score_5=10, score_6=8, score_7=4. 分数_1 = 7,分数_2 = 9,分数_3 = 6,分数_4 = 9,分数_5 = 10,分数_6 = 8,分数_7 = 4。

How do I select this table and display the results according to the best closest values 如何选择此表并根据最接近的值显示结果

This below query doesn't give 100% of what I need: 下面的查询没有给出我需要的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

I think you want greatest() : 我认为您想要greatest()

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

Is this what you want? 这是你想要的吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM