开发者

MySql natural sorting with offset from a certain value

I have the data:

CREATE TABLE IF NOT EXISTS `sort` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `value` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
);

INSERT INTO `sort` (`id`, `value`) VALUES
    (1, 'abc2'),
    (2, 'abc20'),
    (3, 'abc1'),
    (4, 'abc10'),
    (5, 'abc3');

I want to have all the rows starting from a specified id then to the end of that result set to be added all the rows until that specified id and all sorted by value.

So i come out with this:

SET @id=3;
SELECT * FROM sort
ORDER BY 
id=@id DESC, value>=(SELECT value FROM sort WHERE id=@id) DESC, value ASC;

Everything works fine but is not a natural sort. With the query above i get the result ab开发者_开发技巧c1, abc10, abc2, abc20, abc3. The result I'm looking for is abc1, abc2, abc3, abc10, abc20. And of course if I change @id=4 the results should be abc10, abc20, abc1, abc2, abc3.

With the query bellow I get the natural sorting I want.

SELECT * FROM sort ORDER BY LENGTH(value), value; 

So the question is: How can I combine the two ORDER BY clauses into one?


This should work:

SELECT * 
FROM sort 
ORDER BY  
    id=@id DESC,
    LENGTH(value),
    value>=(SELECT value FROM sort WHERE id=@id) DESC, 
    value ASC;`
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜