我正在为招聘信息网站制作搜索功能。为此,我需要首先显示具有匹配标题的列表,然后显示具有匹配描述的作业列表。这是我现在正在使用的查询:
示例:
(SELECT * FROM `jobs` WHERE title LIKE '%java%developer%')
UNION DISTINCT
(SELECT * FROM `jobs` WHERE description LIKE '%java%developer%')
但是,我还需要按时间戳对结果进行排序,以便首先显示最新结果。就像它应该给出具有按时间戳排序的匹配标题的结果,然后是按时间戳排序的具有匹配描述的列表。
答案 0 :(得分:4)
我可能会写类似的查询:
select *, ((title like '%…%')*2 + (description like '%…%')) as rank
from jobs
where title like '%…%'
or description like '%…%'
order by rank desc, time desc
这样,标题和描述匹配的行将首先出现,然后是title-matches,然后是description-matches。我还没有测试过,但通常mysql在将bool转换为int方面做得很好(true:1,false:0)
答案 1 :(得分:3)
尝试此操作,将timestamp
替换为时间戳列的名称
(SELECT *, 1 as unionsorting FROM `jobs` WHERE title LIKE '%java%developer%' ORDER BY timestamp desc)
UNION DISTINCT
(SELECT *, 2 as unionsorting FROM `jobs` WHERE description LIKE '%java%developer%' ORDER BY timestamp desc)
ORDER BY unionsorting
但是做2个查询可能更快(必须进行测试)
SELECT * FROM `jobs` WHERE title LIKE '%java%developer%' ORDER BY timestamp desc
SELECT * FROM `jobs` WHERE description LIKE '%java%developer%' ORDER BY timestamp desc
答案 2 :(得分:1)
已修改以修复...
这有点笨重,但有些变化可行:
SELECT title, description, timestamp_column, min(rank) from
(
(SELECT *, 1 as rank FROM `jobs` WHERE title LIKE '%java%developer%')
UNION
(SELECT *, 2 as rank FROM `jobs` WHERE description LIKE '%java%developer%')
) x
GROUP BY title, description, timestamp_column
ORDER BY min(rank), timestamp_column DESC
这使用GROUP BY
子句代替DISTINCT
答案 3 :(得分:1)
SELECT *
FROM `jobs`
WHERE (title LIKE '%java%developer%' OR description LIKE '%java%developer%')
ORDER BY (CASE WHEN title LIKE '%java%developer%' THEN 0 ELSE 1 END), timestamp_col DESC
答案 4 :(得分:0)
(SELECT * FROM `jobs` A WHERE title LIKE '%java%developer%' ORDER BY A.colDateTime desc)
UNION DISTINCT
(SELECT * FROM `jobs` B WHERE description LIKE '%java%developer%' ORDER BY B.colDateTime desc)