MySQL - 根据同一查询中的参数对结果进行排名

时间:2015-09-18 11:56:08

标签: mysql sql

previous question中,我发现了如何拆分搜索字符串'01 -0023'并搜索两列。现在我还要添加第三列description的结果。但是,我希望首先显示(组,文章)产生的数据(即排名更高/更相关)。这怎么可能?

原始查询: SELECT * FROM ARTICLES WHERE group= substring_index('@search_string', '-', 1) + 0 AND article= substring_index('@search_string', '-', -1) + 0

新查询: SELECT * FROM ARTICLES WHERE (group= substring_index('@search_string', '-', 1) + 0 AND article= substring_index('@search_string', '-', -1) + 0) OR description LIKE '%@search_string%'

2 个答案:

答案 0 :(得分:1)

SELECT * 
FROM ARTICLES 
WHERE (group= substring_index('@search_string', '-', 1) + 0 
    AND article= substring_index('@search_string', '-', -1) + 0) 
OR description LIKE '%@search_string%'
ORDER BY CASE 
    WHEN (group= substring_index('@search_string', '-', 1) + 0 
        AND article= substring_index('@search_string', '-', -1) + 0) THEN 1
    WHEN description LIKE '%@search_string%' THEN 2 END ASC

答案 1 :(得分:0)

您可以将逻辑移至order by

SELECT *
FROM ARTICLES
ORDER BY (`group` = substring_index('@search_string', '-', 1) + 0) DESC,
         (`article` = substring_index('@search_string', '-', -1) + 0) DESC