我有一个像以下的mysql查询:
select * from employee
where name like '%ani%'
我想通过从ani开始来订购我的结果 例如。我的结果应该是: {anil,anirudha,rani,...}先从ani开始,然后是其他角色。
有人可以帮我解决这个问题吗。
答案 0 :(得分:2)
编辑:添加了第二个解决方案。
解决方案1:
select 1 AS OrderField, name
from employee
where name like 'ani%'
UNION ALL
select 2 AS OrderField, name
from employee
where name like '_%ani%'
ORDER BY OrderField, name
解决方案2:
select name, CASE WHEN name LIKE 'ani%' THEN 1 ELSE 2 END OrderField
from employee
where name like '%ani%'
order by OrderField, name
答案 1 :(得分:1)
像
这样的东西select * from employee where name like '%ani%' order by locate('ani', name) asc, name asc
应该做的诀窍......(按整个字符串中子字符串的位置排序)
答案 2 :(得分:0)
您可以使用联合来实现此目的:
select * from employee where name like 'ani%' order by name
union
select * from employee where name like '%ani%' and not name like 'ani%' order by name
答案 3 :(得分:0)
我并不完全确定你在寻找什么。如果您只想按名称排序该查询的结果:
select * from employee
where name like '%ani%'
order by name asc;
答案 4 :(得分:0)
select * from employee
where name like '%'+'ani'+'%'
order by if(SUBSTRING(name, 1, length('ani'))= 'ani', 0,1), name
用于ms sql server将if
替换为case when
使用提供的语法,很容易用您想要的任何值替换'ani'