2010-11-24 83 views
0

有沒有辦法給where子句添加排序順序?對DB2 SQL結果按WHERE CLAUSE排序

例如

SELECT * 
FROM media 
WHERE media_title LIKE 'query' 
OR media_title LIKE 'query string' 
OR media_title LIKE 'query string to search for' 

我想通過的相關搜索是什麼最終用戶輸入到搜索框中,隨着最後where子句是最相關的。

回答

3
SELECT * 
FROM media 
WHERE media_title LIKE 'query' 
    OR media_title LIKE 'query string' 
    OR media_title LIKE 'query string to search for' 
ORDER BY case 
    when media_title LIKE 'query' then 1 
    when media_title LIKE 'query string' then 2 
    when media_title LIKE 'query string to search for' then 3 
end 
0

我覺得這個版本可能會更快,甚至更具可讀性:

SELECT * 
FROM media 
WHERE media_title IN ('query', 
         'query string', 
         'query string to search for') 
ORDER BY case 
    when media_title = 'query'      then 1 
    when media_title = 'query string'    then 2 
    when media_title = 'query string to search for' then 3 
    end