MySQL : exclude record from UNION

Jibeji :

I have an autocomplete field which queries a simple table to match "name containing string".

My concern is that I want to list the exact match first.

I perform an UNION query like that:

SELECT 'exact_match' AS type, name FROM table WHERE name='john'
UNION
SELECT 'match' AS type, name FROM table WHERE name LIKE '%john%'
ORDER BY type, name LIMIT 30

But in case the user types the whole name, the result contains two records (if there is no other %john% in the table):

john
john

How can I exclude the result of one of the two queries if they perfectly match ?

I thought it was the aim of UNION (vs UNION ALL) but this is not the case, certainly because of the 'type' value.

Or maybe there is a better solution to list the exact match first ?

Gosfly :

You can just simply add a where clause in the second query to exclude "perfect match" as you already get them in the first query:

SELECT 'exact_match' AS type, name FROM table WHERE name='john'
UNION
SELECT 'match' AS type, name FROM table WHERE name LIKE '%john%' AND name <> 'john'
ORDER BY type, name LIMIT 30

Or you could rewrite your query this way :

SELECT
  CASE WHEN name = 'john' THEN 'exact_match' ELSE 'match' END AS type,
  name
FROM table
WHERE name like '%john%'

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=21274&siteId=1