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`