在SQL搜索(LIKE)语句中首先赋予列优先级

时间:2010-11-02 16:56:23

标签: sql sql-server

这是我的SQL搜索声明.......

我想以第一优先级返回列 NAME 的值,然后返回列 Desc_Work

Select * from posts
where Province = 'Western_Cape'
and NAME LIKE '%Etienne%' 
or Desc_Work LIKE '%Etienne%'

我必须对此进行哪些更改才能确保首先显示NAME列中的行?

3 个答案:

答案 0 :(得分:11)

ORDER BY CASE
WHEN NAME LIKE '%Etienne%' THEN 1
ELSE 2
END

我也相信你想要where Province = 'Western_Cape' and (NAME LIKE '%Etienne%' or Desc_Work LIKE '%Etienne%')

<强>更新

Select * from posts
where Province = 'Western_Cape'
and (NAME LIKE '%Etienne%' 
or Desc_Work LIKE '%Etienne%')
ORDER BY CASE
WHEN NAME LIKE '%Etienne%' THEN 1
ELSE 2
END

我假设您需要括号中的(NAME LIKE '%Etienne%' or Desc_Work LIKE '%Etienne%') - 您的原始查询会返回(Province = 'Western_Cape' and NAME LIKE '%Etienne%' ) or Desc_Work LIKE '%Etienne%') ...

的记录

答案 1 :(得分:0)

您可以实施全文搜索并对结果进行排名。我认为另一个问题在这里提出了类似的问题:Giving precedence/weight to a column using FREETEXTTABLE

答案 2 :(得分:0)

你可以写下这个:

Select NAME, posts.* from posts where Province = 'Western_Cape' and NAME LIKE 'Etienne%' or Desc_Work LIKE '%Etienne%'