mysql 按特定字符串查询,MySQL命令按特定字符串

本文介绍了一种数据库查询技巧,如何按名称排序时从BB开始并循环,实现非字母顺序。通过示例和SQL查询展示如何让BB在结果中始终靠前,随后是CD,最终返回ID和Name列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I can't seem to find an answer to this one:

Say I have a table like so:

ID Name

------------------------

1 AAAAAAAAA

2 ABAAAAAAA

3 BBAAAAAAA

4 CDAAAAAAA

5 BBAAAAAAA

Is there a way I can order by name - but - start that order from say BB and let it loop back round (instead of from A-Z, go from BB to BA)

The final result would then be:

3 BBAAAAAAA

5 BBAAAAAAA

4 CDAAAAAAA

1 AAAAAAAAA

2 ABAAAAAAA

Does that make sense?

解决方案

If you want the BB to appear at the beginning you can use:

select *

from yourtable

order by case when substring(name, 1, 2) = 'BB' then 0 else 1 end

If you want CD to appear second, then use:

select *

from yourtable

order by

case

when substring(name, 1, 2) = 'BB' then 0

when substring(name, 1, 2) = 'CD' then 1

else 2 end, name

Result for second query:

| ID | NAME |

------------------

| 3 | BBAAAAAAA |

| 5 | BBAAAAAAA |

| 4 | CDAAAAAAA |

| 1 | AAAAAAAAA |

| 2 | ABAAAAAAA |

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值