mysql字符串排序,在MySQL中对字符串字符进行排序

I have a column (varchar(255)) in a mysql table, lets call it "word". How to write a select query that returns me the values in this column sorted by characters in the string?

For example, if one of the records had the word "earth" it should return me "aehrt" and so on, for all the rows. Is there any way to do it in a single query?

解决方案

Probably highly inefficient, but without any need for user-defined functions:

SELECT GROUP_CONCAT(LETTER SEPARATOR '') AS ReOrderedLetters

FROM ( SELECT 'A' as LETTER FROM

UNION ALL

SELECT 'B' as LETTER FROM

UNION ALL

SELECT 'C' as LETTER FROM

UNION ALL

SELECT 'D' as LETTER FROM

...

UNION ALL

SELECT 'Y' as LETTER FROM

UNION ALL

SELECT 'Z' as LETTER FROM

) alpha

EDIT

I had to come up with a better alternative before going to bed, otherwise I'd never have got to sleep; so here's a much cleaner and more efficient alternative.

I created a table called letters with a single column of VARCHAR(1) called letter;

then populated that table with the letters A to Z

CREATE TABLE IF NOT EXISTS `letters` (

`letter` varchar(1) NOT NULL,

PRIMARY KEY (`letter`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `letters` (`letter`) VALUES

('A'),('B'),('C'),('D'),('E'),('F'),('G'),('H'),('I'),('J'),('K'),('L'),('M'),

('N'),('O'),('P'),('Q'),('R'),('S'),('T'),('U'),('V'),('W'),('X'),('Y'),('Z');

then:

select U.`name`,

GROUP_CONCAT(L.`letter`

ORDER BY L.`letter` ASC

SEPARATOR '') AS ReOrderedLetters

FROM `users` U

LEFT JOIN `letters` L ON POSITION(L.`letter` IN UPPER(U.`name`)) > 0

GROUP BY U.`name`

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值