简体   繁体   中英

mysql sort results by relevance case issue

I am trying to sort Movies based on their Titles Relevance.

Here are the raw Mysql Query Results.

21126   A Frozen Flower 
4557    Cashback 
4504    Frozen 
36645   Frozen
509     Frozen Assets 
20649   Frozen Flesh 
24752   Frozen Kiss 
25675   Frozen Land 
4783    Frozen River 
11798   Frozen River 
11856   Frozen Scream
21755   Frozen Silence 
26333   Frozen Thrills 
8532    Frozen Water 
16196   God Don't Make the Laws 
6158    The Frozen Ground 
28160   The Thaw 
7320    Winter of Frozen Dreams

Current Code I am using

SELECT * FROM `movies` 
    WHERE `Title` LIKE '%Frozen%' 
    OR `other_title` LIKE '%Frozen%'  

    GROUP BY `Title` ORDER BY CASE 
    WHEN `Title` = 'Frozen' THEN 0
    WHEN `Title` like 'Frozen%' THEN 1
    WHEN `Title` like '% %Frozen% %' THEN 2
    WHEN `Title` like '%Frozen' THEN 3
    ELSE 4
    END, `Title`

and here are the results

4504    Frozen
509     Frozen Assets
20649   Frozen Flesh
24752   Frozen Kiss
25675   Frozen Land
4783    Frozen River
11856   Frozen Scream
21755   Frozen Silence
26333   Frozen Thrills
8532    Frozen Water
21126   A Frozen Flower
6158    The Frozen Ground
7320    Winter of Frozen Dreams
4557    Cashback
16196   God Don't Make the Laws
28160   The Thaw

Ok The results look pretty good except that where there were duplicate Titles they were not displayed.

Any Idea how to Fix this issue??

The duplicate is being removed by the group by . Just remove that:

SELECT *
FROM `movies` 
WHERE `Title` LIKE '%Frozen%' OR `other_title` LIKE '%Frozen%'  
ORDER BY (CASE WHEN `Title` = 'Frozen' THEN 0
               WHEN `Title` like 'Frozen%' THEN 1
               WHEN `Title` like '% %Frozen% %' THEN 2
               WHEN `Title` like '%Frozen' THEN 3
               ELSE 4
          END), `Title`

It sounds to me like you might want to use natural language search functionality in MySQL. This will allow you to match search criteria against multiple fields and have them automatically sorted by relevance.

See this link for more details: http://dev.mysql.com/doc/refman/5.5/en/fulltext-natural-language.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM