Quantcast
Channel: MySQL
Viewing all articles
Browse latest Browse all 14

SQL: Use CASE for Relevance column

$
0
0
What?
So this is a quick note to myself as I was playing with the relevance heuristics of a query. This example adds a column of relevance and sorts the rows accordingly.

How?
This has to be a real quick one for a dropdown search field which has to find relevant terms to autofill/autocomplete a search form:
-- where @ThisSearch is a posted (and sanitized) variable

SET @ThisSearch:="Brains";

SELECT
        columnID,
        columnFullName,
        CASE
                WHEN columnFirstName LIKE @ThisSearch THEN 20
                WHEN columnFullName LIKE @ThisSearch THEN 10
                WHEN columnLastName LIKE @ThisSearch THEN 10
                WHEN columnFullName LIKE @ThisSearch THEN 1
        END as relevance
FROM
        myTable
WHERE
        s.columnPublished <= NOW()
        AND (
                SOUNDEX(@ThisSearch)=columnFullSoundex
                OR columnFullName LIKE @ThisSearch
        )
ORDER BY relevance DESC, columnFullName ASC

Viewing all articles
Browse latest Browse all 14

Trending Articles