mysql sort results by relevance case issue

1.2k views Asked by At

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??

2

There are 2 answers

0
Gordon Linoff On BEST ANSWER

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`
0
Mike Brant On

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