assume that we are performing search using keywords: keyword1, keyword2, keyword3
there are records in database with column \"name\":
1: John Doe 2: Samue
SELECT *
from
(
SELECT u.*, 1 OrderNum
FROM users
WHERE (name LIKE "%John%")
UNION
SELECT u.*, 2 OrderNum
FROM users
WHERE (name LIKE "%Doe%")
)
Order by OrderNum
My example will Order all of the John
's Alphabetically followed by the Doe
's.
ORDER BY CASE
WHEN name LIKE "John%Doe" THEN CONCAT('a',name)
WHEN name LIKE "John%" THEN CONCAT('b',name)
WHEN name LIKE "%Doe" THEN CONCAT('c',name)
ELSE name
END
To build on RedFilter's answer, you could make the rows that have both keywords to be at the top:
order by case
when (name LIKE "%John%" and name LIKE "%Doe%") then 1
when name LIKE "%John%" then 2
when name LIKE "%Doe%" then 3
end
order by case
when name LIKE "%John%" then 1
when name LIKE "%Doe%" then 2
else 3
end
Read up on Boolean Fulltext Searches, with which you can do ordering.