SQL优先级条件

时间:2015-11-17 17:44:18

标签: sql

我有一个类似的查询:

SELECT * FROM mytable WHERE  (`field1` LIKE '%search%' OR `field2` LIKE '%search%' OR `field3` LIKE '%search%')

关键字search可以是任何其他字词。如何设置此查询的优先级?我想先在field1中,field2之后,然后在field3中搜索。

因此,如果我在field1中找到关键字searchsearchfield1行必须在我的结果集中排在第一位。

我该怎么做?

4 个答案:

答案 0 :(得分:3)

您可以通过以下方式执行此操作:

SELECT * 
FROM mytable 
WHERE  (`field1` LIKE '%search%' OR `field2` LIKE '%search%' OR `field3` LIKE '%search%')
ORDER BY 
CASE 
  WHEN `field1` LIKE '%search%' THEN 1
  WHEN `field2` LIKE '%search%' THEN 2
  WHEN `field3` LIKE '%search%' THEN 3
  ELSE 4
END 

答案 1 :(得分:1)

你最好拆分查询并将它们联合起来。

select *
    from (
    SELECT 1 as s, * FROM mytable WHERE  ('field1' LIKE '%search%')
    union
    SELECT 2 as s, * FROM mytable WHERE  ('field2' LIKE '%search%')
    union
    SELECT 3 as s, * FROM mytable WHERE  ('field3' LIKE '%search%')
) a 
order by s

答案 2 :(得分:0)

按布尔结果排序:

SELECT * FROM mytable WHERE
    (
      `field1` LIKE '%search%' OR `field2` LIKE '%search%' 
      OR `field3` LIKE '%search%'
    )
order by `field1` LIKE '%search%' DESC

您需要DESC,因为默认情况下false通常在true

之前订购

答案 3 :(得分:0)

if exists (select top 1 * form mytable where 'field1' like '%search%')
 select * form mytable where 'field1' like'%search%'
else if exists (select top 1* form mytable where 'field2' like '%search%')
 select * form mytable where 'field2' like'%search%'
else
 select * form mytable where 'field3' like'%search%'