我有一个类似的查询:
SELECT * FROM mytable WHERE (`field1` LIKE '%search%' OR `field2` LIKE '%search%' OR `field3` LIKE '%search%')
关键字search
可以是任何其他字词。如何设置此查询的优先级?我想先在field1
中,field2
之后,然后在field3
中搜索。
因此,如果我在field1中找到关键字search
,search
中field1
行必须在我的结果集中排在第一位。
我该怎么做?
答案 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%'