mysql返回顺序,从MySQL返回结果时的数字顺序

I have the following types of titles in a table in my db:

Topic 1 blah blah

Topic 2 blah blah

Topic 3 blah blah

...

Topic 10 blah blah

Topic 11 blah blah

etc...

The select query will always return the results like this:

Topic 1 blah

Topic 10 blah blah

Topic 11 blah

...leaving out Topic 2, Topic 3 etc... until after all the teens will I get Topic 2 etc...

How can I get my results as:

Topic 1

Topic 2

Topic 3

.... all the way to Topic 9 and only then have Topic 10?

解决方案

This is a problem with your database design. The topic number should be stored as an integer. If you can't change the design, try this query instead:

SELECT title

FROM table1

ORDER BY CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(title, ' ', 2), ' ', -1)

AS UNSIGNED);

Result:

'topic 1 foo'

'topic 2 bar'

'topic 10 baz'

Test data:

DROP TABLE IF EXISTS table1;

CREATE TABLE table1 (title VARCHAR(100) NOT NULL);

INSERT INTO table1 (title) VALUES

('topic 1 foo'),

('topic 2 bar'),

('topic 10 baz');

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值