我想允许用户根据同一个表(目标和名称)中的两个不同字段进行搜索。但是,如果目标上存在完全匹配,我希望它优先于订单,因此首先显示目标为dis的行。
将不胜感激。
select
Id
,[target]
,[name]
,[extrafield1]
,[extrafield2]
,[extrafield3]
From [inventory]
where [target] LIKE 'dil%' OR [name] LIKE '%dil%'
答案 0 :(得分:2)
这样的东西?
select
Id
,[target]
,[name]
,[extrafield1]
,[extrafield2]
,[extrafield3]
From [inventory]
where [target] LIKE 'dil%' OR [name] LIKE '%dil%'
order by
case when target = 'dil' then 0 else 1 end asc,
case when name = 'dil' then 0 else 1 end asc
答案 1 :(得分:1)
似乎是IF/ELSE语句
的一个很好的用例IF EXISTS(SELECT 1 FROM [inventory]
where [target] LIKE 'dil%')
BEGIN
select
Id
,[target]
,[name]
,[extrafield1]
,[extrafield2]
,[extrafield3]
From [inventory]
where [target] LIKE 'dil%'
END
ELSE
BEGIN
select
Id
,[target]
,[name]
,[extrafield1]
,[extrafield2]
,[extrafield3]
From [inventory]
where [name] LIKE '%dil%'
END
答案 2 :(得分:1)
尝试使用union ..
select
Id
,[target]
,[name]
,[extrafield1]
,[ Extrafield2]
,[extrafield3]
From [inventory]
where [target] LIKE 'dil%'
Union
select
Id
,[target]
,[name]
,[extrafield1]
,[extrafield2]
,[ Extrafield3]
From [inventory]
where [name] LIKE '%dil%'
答案 3 :(得分:1)
不要在字符串的两边使用widlcard,即。 %string%这将导致对表的串行读取。把它放在右侧。
select
Id
,[target]
,[name]
,[extrafield1]
,[extrafield2]
,[extrafield3]
,case when [target] = 'dil' or [name] = 'dil' then 1 else 2 end as rank -- to display your ranking
From [inventory]
where [target] LIKE 'dil%' or [name] like 'dil%'
order by case when [target] = 'dil' or [name] = 'dil' then 1 else 2 end