最近小弟在做一个小项目,这个项目中需要对数据库的查询结果进行排序。
我做的是一个小小的搜索功能,具体是这样的;
我可以搜几个字段 比如我搜       ‘清华’,‘出版社’;
回到数据库里检索符合这个字段要求的条目,可是肯定有的结果只含有‘清华’,有的结果只含有‘出版社’,有的结果既含有‘清华’,又含有‘出版社’-----
现在有没有什么方法能够做到  以下要求:
结果即含有‘清华’又含有‘出版社’的字段条目排在最前面,至于满足要求的条目的位置不用考虑;
结果只含有 ‘清华’字段的条目排在中间位置;
结果只含有‘出版社’ 字段的条目排在最后位置;假设 现在张表 Book 有字段 book_id ; book_name ; book_press;
有如下条目:
1  吾国与吾民 清华大学出版社
2  京华烟云     安徽大学出版社
3  品三国         清华大通出版社
4  傲慢与偏见  清华Press我需要查询结果这样排列
 book_id ; book_name ; book_press;
1   吾国与吾民 清华大学出版社
2   品三国         清华大通出版社
3   傲慢与偏见  清华Press
4   京华烟云     安徽大学出版社其中第一第二条谁前谁后无所谓!
求赐教!

解决方案 »

  1.   


    select *
    from tb
    order by (case when charindex('清华',book_press) > 0 and charindex('出版社',book_press) > 0 then 0
                   when charindex('清华',book_press) > 0 and charindex('出版社',book_press) = 0 then 1
                   when charindex('清华',book_press) = 0 and charindex('出版社',book_press) > 0 then 2
                   else 3 end),book_id --试试!
      

  2.   

    select * from tb order by
    patindex('%清华%出版社%',book_press) desc,
    patindex('%清华%',book_press) desc
      

  3.   


    declare @table table (book_id int,book_name varchar(10),book_press varchar(14))
    insert into @table
    select 1,'吾国与吾民','清华大学出版社' union all
    select 2,'京华烟云','安徽大学出版社' union all
    select 3,'品三国','清华大通出版社' union all
    select 4,'傲慢与偏见','清华Press'select * from @table 
    order by 
    sign(charindex('清华',book_press))+sign(charindex('出版社',book_press)) desc,
    charindex('出版社',book_press) desc
    /*
    book_id     book_name  book_press
    ----------- ---------- --------------
    1           吾国与吾民      清华大学出版社
    3           品三国        清华大通出版社
    2           京华烟云       安徽大学出版社
    4           傲慢与偏见      清华Press
    */