1

不幸的是,我的 SQL 很生疏。我目前有这样的声明:

SELECT field1, field2, field3 FROM table_name WHERE
    field1 = 'A' OR field2 = 'B' OR field3 = 'C' ORDER BY
        CASE WHEN field1 = 'A' THEN 1 ELSE 0 END +
        CASE WHEN field2 = 'B' THEN 1 ELSE 0 END +
        CASE WHEN field3 = 'C' THEN 1 ELSE 0 END
    DESC LIMIT 1;

这个查询正确地找到了分别与field1field2、、和的“理想”最相似的项目。但是,我也希望能够找到“匹配”字段的数量。似乎我应该能够轻松获得它,因为我已经在执行该计算,但我不确定如果没有另一个子查询如何。field3ABC

任何帮助将非常感激!

4

1 回答 1

2

更新

SELECT field1, field2, field3,
       CASE WHEN field1 = 'A' THEN 1 ELSE 0 END +
       CASE WHEN field2 = 'B' THEN 1 ELSE 0 END +
       CASE WHEN field3 = 'C' THEN 1 ELSE 0 END match_count
  FROM table_name 
 WHERE field1 = 'A' OR field2 = 'B' OR field3 = 'C' 
 ORDER BY match_count DESC

在这种特殊情况下(对于MySql),您可以替换CASE(fieldX = 'N')

SELECT field1, field2, field3,
       (field1 = 'A') + (field2 = 'B') + (field3 = 'C') match_count
  FROM table_name 
 WHERE field1 = 'A' OR field2 = 'B' OR field3 = 'C' 
 ORDER BY match_count DESC

现在根据 match_count 使用HAVING子句限制结果集

SELECT field1, field2, field3,
       (field1 = 'A') + (field2 = 'B') + (field3 = 'C') match_count
  FROM table_name 
 WHERE field1 = 'A' OR field2 = 'B' OR field3 = 'C' 
HAVING match_count > 1
 ORDER BY match_count DESC

这是上述所有查询的SQLFiddle演示

于 2013-06-28T06:50:14.530 回答