2013-06-28 78 views
1

不幸的是,我的SQL非常生疏。我現在有一個說法是這樣的:在ORDER BY語句中計算CASE

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; 

該查詢正確查找最相似的項目到field1field2field3分別爲ABC的「理想」。但是,我也希望能夠找到「匹配」字段的數量。看起來我應該能夠很容易地得到它,因爲我已經在執行該計算,但是我不確定沒有另一個子查詢。

任何幫助將不勝感激!

回答

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),你可以根據match_count使用替代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 

我們限制結果集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演示上述所有查詢

+0

我一直在尋找的正是這樣!感謝代碼和演示。 – JacobEvelyn

+0

不用等幾分鐘,我不會讓我接受它,對不起。我最初的問題:是否有一種簡單的方法可以將查詢結果限制爲match_count'>某個閾值,而不輸出'match_count'? – JacobEvelyn

+0

我想我可以再次執行'CASE'並將它放在'AND'子句中。 – JacobEvelyn