简体   繁体   English

如何找到最接近的结果?

[英]How to find the closest result?

Lets say I have an array with fields A, B, C, D, E, F whose value can be a random number假设我有一个包含字段 A、B、C、D、E、F 的数组,其值可以是random number

I use these fields to make a query WHERE A = 'random number' AND B = 'random number'... AND F = 'random number'我使用这些字段进行查询WHERE A = 'random number' AND B = 'random number'... AND F = 'random number'

If the result is empty then I remove last field from my array then run query WHERE A = 'random number' AND B = 'random number'... AND E = 'random number'如果结果为空,则从数组中删除最后一个字段,然后运行查询WHERE A = 'random number' AND B = 'random number'... AND E = 'random number'

This process repeats until I get the result.这个过程重复,直到我得到结果。 Now, I found a new case where if I remove D field only and run the query, it returns the result.现在,我发现了一个新案例,如果我只删除D字段并运行查询,它会返回结果。

I am not sure how to handle this case.我不确定如何处理这种情况。

One option would be to count how many columns in the row equal to that number, and take the row with the most matches.一种选择是计算行中有多少列等于该数字,并取匹配最多的行。 MySQL has a neat ability to treat boolean values as 0s and 1s in numeric contexts, so this can be done relatively easily (but note the operator precedence and the required parentheses): MySQL 具有在数字上下文中将 boolean 值视为 0 和 1 的巧妙能力,因此这可以相对容易地完成(但请注意运算符优先级和所需的括号):

SELECT   *
FROM     mytable
ORDER BY (a = random_number) + 
         (b = random_number) + 
         (c = random_number) + 
         (d = random_number) + 
         (e = random_number) DESC
LIMIT    1

If you really want to remove the last column at each step, then:如果您真的想在每个步骤中删除最后一列,那么:

select t.*
from t
order by (a, b, c, d, e) = ($a, $b, $c, $d, $e) desc,
         (a, b, c, d) = ($a, $b, $c, $d) desc,
         (a, b, c) = ($a, $b, $c) desc,
         (a, b) = ($a, $b) desc,
         a = $a desc
limit 1;

Note: If there is no match then this will still return a row.注意:如果没有匹配,那么这仍然会返回一行。 That seems to follow your pattern.这似乎遵循你的模式。

You can also use:您还可以使用:

select t.*
from t
order by (a = $a) desc,
         (b = $b) desc,
         (c = $c) desc,
         (d = $d) desc
         (e = $e) desc
limit 1;

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

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