日期:2014-05-17  浏览次数:20792 次

数据库查询并且排序问题
数据库中product有两列,一列name,一列Description
select * from product p where p.name like '%幸福%' or p.Description like '%幸福%';
 
能查出名字中和描述中包含幸福的的product
问题:怎样让名字中包含‘幸福’字段的product排在前边?

------解决方案--------------------
用了一个比较笨的法子,多一个flg列


select p.*,
       case
         when instr(name, '幸福') > 0 then
          1
         else
          null
       end flg
  from product p
 where p.name like '%幸福%'
    or p.Description like '%幸福%'
 order by flg nulls last

------解决方案--------------------
select * from product p where p.name like '%幸福%' or p.Description like '%幸福%'
order by instr(p.name, '幸福') desc;