场景:
一个文章表(T_Article),里面有两个字段,标题(title)和内容(content)
用户输入一个keyword,从文章表的title和content中搜索记录
SQL语句如下:
SELECT * FROM T_Article WHERE title LIKE '%keyword%' OR content LIKE '%keyword%';
问题来了,我现在需要对结果集进行排序,需要先把标题匹配的记录放在前面,内容匹配但是标题不匹配的记录放在后面,
请问SQL语句怎么写,或者有什么解决方法。
分数不多,真心求助
------解决方案--------------------
select *,1 as aa from tb where name like '%1%'
union
select *,2 as aa from tb where pay like '%1%'
order by aa
------解决方案--------------------
- SQL code
--对结果再进行一次title LIKE '%keyword%'就可以了;with cte as( SELECT * FROM T_Article WHERE title LIKE '%keyword%' OR content LIKE '%keyword%')select * from cteWHERE title LIKE '%keyword%'--或select * from ( SELECT * FROM T_Article WHERE title LIKE '%keyword%' OR content LIKE '%keyword%') tWHERE t.title LIKE '%keyword%'
------解决方案--------------------
- SQL code
select * from( SELECT *,xh=1 FROM T_Article WHERE title LIKE '%keyword%' union all select *,xh=2 FROM T_Article WHERE content LIKE '%keyword%')aorder by xh
------解决方案--------------------
- SQL code
SELECT * FROM T_Article WHERE title LIKE '%keyword%' OR content LIKE '%keyword%'order by case when title LIKE '%keyword%' then 0 else 1 end