SQLite最多匹配多列的行与值

时间:2016-03-14 05:51:19

标签: database sqlite search rows

测试表

ID  a   b   c   d   e   (f to z)
--------------------------------
0   2   7   9   0   8   ...
1   4   5   6   3   0   ... 
2   1   5   6   2   9   ...
3   1   0   8   2   3   ...
4   2   1   6   9   5   ...
5   1   5   6   2   3   ...
6   2   3   4   1   0   ...

我想找到与查询匹配最多列的行。我现在拥有的是

select ID from test where a = 1, b = 5, c = 6, d = 2, e = 3, ... (same with f to z)

上述样本的所需输出为:5,2,3,1,4

如何编写这样的查询?

1 个答案:

答案 0 :(得分:1)

要在多列上找到最接近的匹配,最简单的方法可能是计算列式匹配的数量,然后按降序排序。

SELECT ID
FROM myTable
ORDER BY 
  CASE WHEN a = 1 THEN 1 ELSE 0 END +
  CASE WHEN b = 5 THEN 1 ELSE 0 END +
  CASE WHEN c = 6 THEN 1 ELSE 0 END +
  CASE WHEN d = 2 THEN 1 ELSE 0 END +
  CASE WHEN e = 3 THEN 1 ELSE 0 END DESC;

# ID: 5 2 3 1 4 0 6

An SQLfiddle to test with