sql语句查询问题
本文介绍了sql语句查询问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
问题是课程搜索,关键词为数据,返回名称或描述中包含此关键词的课程,排序规则:名称包含的在先,内容包含的在后,分别按照课程创建的时间倒序,一开始我写了这个答案:
`(select * from t_course
where name like '%数据%'
order by createdat desc) union all
(select * from t_course
where description like '%数据%'
order by createdat desc);`
但是获得的结果中,时间不是降序排列的,而按照在表中的默认顺序。两部分分别查询时时间顺序正确。
求帮助解决。
解决方案
应该是union all
破坏了原来的顺序。还有一个要注意的问题是union all
可能引入重复数据。比如数据库系统。
不妨弃用union all
,用case
的方式在查询的时候增加一列match_type
,用来表示匹配的类型(无匹配=0,名称匹配=1,内容匹配=2),最后先按照匹配类型再按照创建时间排序。例如(未经测试):
select *,
case when name like '%数据%' then 1
when description like '%数据%' then 2
else 0
end as match_type
from t_course
where match_type > 0
order by match_type asc, createdat desc;
这篇关于sql语句查询问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文