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);`

但是获得的结果中,时间不是降序排列的,而按照在表中的默认顺序。两部分分别查询时时间顺序正确。
图片描述求帮助解决。

阅读 2.6k
3 个回答

应该是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;

select * from (select * from t_course 
where name like '%数据%' 
order by createdat desc) as m union all select * from
(select * from t_course
where description like '%数据%'
order by createdat desc) as n;
select * from (select * from pre_portal_article_title where title like '%CM11%' order by dateline desc) as n union all select * from (select * from pre_portal_article_title where title like '%CM11%' order by dateline desc) as m;

图片描述

新手上路,请多包涵

同学南大软院的吧??

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进