2011-09-28 100 views
0

我已经表叫Property和数据就像SQL查询顺序输出

pid  city   state   state_abb  address1 address2 
    x1  NewCity  NHANy    NH   xxxx  gfg 
    x2  Gloucester  Manchestar   MA   newAde xxxx 
    x3  OtherC   NewYork   NY   yyyy 

我想搜索的关键字查询,显示订单像(州或state_abb),城市,地址1,adress2

对于前:

如果我结果输出应该

pid city   state  state_abb address1 address2 
    x3 OtherC  NewYork   NY  yyyy 
    x1 NewCity  NHANy   NH  xxxx  gfg 
    x2 Gloucester Manchester  MA  newAde  xxxx 
关键词搜索

我不想要不匹配的行。我只想显示匹配的行。

在此先感谢

+4

那你试试?请张贴您尝试的查询并解释您遇到问题的位置。 – Oded

+0

@Oded同意,我不想键入整个查询,但很愿意帮助... – RedFilter

+0

谢谢您的回复我在SQL差这么PLZ给我一些想法,我可以尝试,当然 – Sree

回答

3

它认为问题是如何命令结果,而不是如何执行搜索。试试这个作为你的ORDER BY子句

order by 
case when charindex('NEW',state) >0 then 1000 else 0 end desc, 
case when charindex('NEW',city) >0 then 100 else 0 end desc, 
case when charindex('NEW',address) >0 then 10 else 0 end desc 

Where子句中只得到匹配的行

select * from Property where 
     city  like '%New%' or 
     state like '%New%' or 
     address1 like '%New%' or 
     address2 like '%New%' 
+0

三江源其工作 – Sree

+0

欢迎您... – Sparky

+0

u能告诉我查询我不想无与伦比的数据行 – Sree

0

你可以尝试这样的事:

SELECT pid, city, state, stat_abb, address1, address2 
from property 
where city like '%New%' 
OR state like '%New%' 
OR address1 like '%New%' 
+1

,在搜索使用多个字段以'或'并且还使用'LIKE'与一家领先的''%将完全彻底避免任何可能的指数,因此性能将是可怕的慢.... –

+0

@marc_s表示同意,但与他的信息只要给他一个startng点 – Taryn

+0

它给人当然相同的输出 – Sree

0

这应该让你开始:

select * from Property where 
    city  like '%New%' or 
    state like '%New%' or 
    address1 like '%New%' or 
    address2 like '%New%' 

我假设你不想看pid柱。

+1

,与'或'几个字段搜索,也使用'LIKE'与一家领先的''%将完全彻底避免任何可能的指标来使用,从而性能将会非常慢...... –

+0

@marc_s同意了,但OP没有给出太多的上下文。这可能是非常有用的,如果表规模并不大 –

+0

确实 - 只是想指出的是,这种方法不是最好的扩展到大量的行....对于小的数字,这是无关紧要的 –

0
select * 
from Property 
order by case 
      when state  like 'New%' then 1 
      when state_abb like 'New%' then 1 
      when city  like 'New%' then 2 
      when address1 like 'New%' then 3 
      when address2 like 'New%' then 4 
     end