I am trying search two columns in a table, ie title and description. but I want to search title first and then description. so all rows that matches title comes first and all rows that matches description comes second
can I implement this using a single SQL query ?
I suppose this should be efficient
SELECT COLA
(
SELECT TITLE AS COLA, 'T' AS IND
FROM TABLE
UNION ALL
SELECT DESCRIPTION AS COLA, 'D' AS IND
FROM TABLE
)
ORDER BY COLA, IND DESC
You can do a UNION and first search in title and give those values a column with 0 and 1 for description. Then you ORDER BY that column:
SELECT col1,col2,col3
FROM
(SELECT col1,col2,col3 ,0 AS ord
FROM table1
WHERE title LIKE "%searchQuery%"
UNION
SELECT col1,col2,col3, 1
FROM table1
WHERE description LIKE "%searchQuery%"
) a
ORDER BY ord ASC;
This way, records that matched in title will appear first.
You can also use a case statement so it doesn't have to go through the whole table twice.
SELECT col1,col2,col3,
Case
WHEN title LIKE '%searchQuery%' THEN 0
WHEN description LIKE '%searchQuery%' THEN 1
END
AS ord
FROM table1
WHERE ord is not null
ORDER BY ord;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.