2015-08-27 80 views
1

我詢問與文本字段的表訂購數量最多的匹配字段

| 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 

回答

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 

UPDATE按照@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 
+0

你能按順序做IF嗎? – Neal

+0

這是一個聰明的解決方案。 – dlporter98

+0

@尼爾我不明白你在問什麼?你能解釋一下你的問題嗎? – Alex

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

在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')才能獲得正確的結果。