我正在查询带有文字字段的表格
| ID | Field1 | Field2 | Field3 |
| 1 | a | random | random |
| 2 | a | b | random | <- second best match
| 3 | random | b | random |
| 4 | a | b | c | <- best match
SELECT *
FROM table
WHERE (Field1 = 'a' OR Field2 = "b" OR Field3 = "c")
所有行都遵循WHERE中的条件,但我需要对结果进行排序,以便考虑匹配字段的数量以便返回
4, 2, 1, 3
答案 0 :(得分:5)
http://sqlfiddle.com/#!9/b9361/7
SELECT t.*,
IF(Field1 = 'a',1,0) aFlag,
IF(Field2 = "b",1,0) bFlag,
IF(Field3 = "c",1,0) cFlag
FROM table1 t
WHERE (Field1 = 'a' OR Field2 = "b" OR Field3 = "c")
ORDER BY (aFlag+bFlag+cFlag) DESC
更新根据可能有用的@Neal评论:
SELECT t.*
FROM table1 t
WHERE (Field1 = 'a' OR Field2 = "b" OR Field3 = "c")
ORDER BY (IF(Field1 = 'a',1,0) +
IF(Field2 = "b",1,0) +
IF(Field3 = "c",1,0) ) DESC
答案 1 :(得分:2)
select id, (if(Field1 = 'a', 1, 0) + if(Field2 = "b", 1, 0) + if(Field3 = "c", 1, 0)) c
from table
order by c desc
答案 2 :(得分:2)
当MySQL将布尔表达式计算为1或0时,聪明的solution by Alex可以进一步简化为:
SELECT * FROM table1
WHERE (Field1 = 'a' OR Field2 = 'b' OR Field3 = 'c')
ORDER BY ((Field1 = 'a') + (Field2 = 'b') + (Field3 = 'c')) DESC
请注意,这取决于表达式中的字段不为空。如果它可以为null,则需要使用IF(Field1 = 'a',1,0)
或(coalesce(Field1,0) = 'a')
才能获得正确的结果。