如有一个表有三个字段,url,title,text 现在我要查询这三个字段中含有“ABC”的纪录,现在要求url含有的“ABC”最先筛选出来,title含有“ABC”次之,最后再筛选出text含有“ABC”,也就是说查询出来的结果,url含有“ABC”的排在最前,title含有“ABC”次之,text含有“ABC”排在最后。
create table st(
  id int primary key,
  url varchar2(50),
  title varchar2(100),
  text varchar2(1000)
)
insert into st values(1, 'http://312312', 'ABC123', '1231231');
insert into st values(2, 'http://2ABC31', '312jf1', '1231231');
insert into st values(3, 'http://312312', '456123', '1231ABC');
insert into st values(4, 'http://2312312', 'ABC345', '1231231');
insert into st values(5, 'http://312312', '24234', '1231231');
insert into st values(6, 'http://12312', '12ABC2312', '12ABC231');
insert into st values(7, 'http://112312', '12123213', '12ABC231');
insert into st values(8, 'http://1ABC12', '12321312', '12ABC1231');请高手们看看这个sql怎么写,谢谢!

解决方案 »

  1.   


    18:34:58 SCOTT@tdwora > select * from st
    18:35:23   2  where instr(url,'ABC')>0
    18:35:23   3     or instr(title,'ABC')>0
    18:35:23   4     or instr(text,'ABC')>0
    18:35:23   5  order by decode(instr(url,'ABC'),0,0,1) desc,
    18:35:23   6           decode(instr(title,'ABC'),0,0,1) desc,
    18:35:23   7           decode(instr(text,'ABC'),0,0,1) desc;        ID URL                                                TITLE                TEXT
    ---------- -------------------------------------------------- -------------------- --------------------
             8 http://1ABC12                                      12321312             12ABC1231
             2 http://2ABC31                                      312jf1               1231231
             6 http://12312                                       12ABC2312            12ABC231
             1 http://312312                                      ABC123               1231231
             4 http://2312312                                     ABC345               1231231
             7 http://112312                                      12123213             12ABC231
             3 http://312312                                      456123               1231ABC已选择7行。
      

  2.   

    相对于楼上的兄弟伙,下面的思路略显累赘了SELECT id,url,title,text FROM 
    (
      SELECT st.*,
      Decode(InStr(url,'ABC'),0,4,1)order1,
      Decode(InStr(title,'ABC'),0,4,2)order2,
      Decode(InStr(text,'ABC'),0,4,3)order3
      FROM st WHERE InStr(url,'ABC')>0 OR InStr(title,'ABC')>0 OR InStr(text,'ABC')>0
    )ORDER BY ORDER1,ORDER2,ORDER3;