Here's my query:
SELECT name, 1 as rank
FROM names
WHERE name LIKE '%abc%'
UNION
SELECT name, 2 as rank
FROM names
WHERE name LIKE '%xyz%'
ORDER BY rank
The problem is duplicate rows won't be combined by UNION since they would differ in the rank column. Now, how would I hide the custom column rank but still use it in ORDER BY clause? Thank you.
EDIT:
I'm actually trying to sort by relevance, eg., whole words && exact phrase first, whole words && non-exact second, non-whole && non-exact third, and so on.
Forget the
union
and subqueries. Just do:Note: If you are concerned about duplicates, you can use
select distinct name
.Try not combining with union, but use a case statement instead. This avoids your duplicate issue.
It looks like you want to select all names with 'abc' from names and then select names with 'xyz'.
With this query anything with 'abc' is ranked 1 and anything with 'xyz' (but not 'abc') is ranked 2.
In our where clause we only select names with 'abc' or 'xyz'. The case applies 1 to 'abc' and all other rows ('xyz' only) get 2. Ordering should work now with no duplication