I am trying to make a MySQL query for a "search" in one of my applications. This is what I currently have:
(SELECT id, title, 1 AS `order` FROM tasks WHERE title LIKE '%Task%Test%') UNION DISTINCT (SELECT id, title, 2 AS `order` FROM tasks WHERE title LIKE '%Task%' AND title LIKE '%Test%') ORDER BY `order` ASC; The second query of the UNION kind of acts as a fallback for the first one, since the first query expects the words to be in the same order. (The amount of words is dynamic, depending on the search query.)
In the results, I want to show the results of the first query first, because those are more precise. To do this, I tried to add an extra column to the results: order.
My problem is that DISTINCT only works for rows that are entirely identical, which is not the case for my rows, because of the orders column.
Example
Table:
id title 1 'Test Task' 2 'The Second Test Task' 3 'A Third Task For Testing' 4 'A Fourth Test' Result:
id title order 3 'A Third Task For Testing' 1 1 'Test Task' 2 2 'The Second Test Task' 2 3 'A Third Task For Testing' 2 What I want:
id title order 3 'A Third Task For Testing' 1 1 'Test Task' 2 2 'The Second Test Task' 2 Anyone who can help me?
Thanks in advance!
WHERE title LIKE '%Test%Task%'first condtion already got the one where Task is first. So the remaining if also have both mean Test is first'%Test%Task%With%More%Words%', for example). Then I have to check for all possible orders, which has a big effect on the execution time. This approach should be much faster.