MySql自然排序与某个值的偏移量
我有数据:
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');
我希望将从指定 id 开始的所有行添加到该结果集末尾的所有行,直到指定 id 为止,并且所有行均按值排序。
所以我得出这样的结论:
SET @id=3;
SELECT * FROM sort
ORDER BY
id=@id DESC, value>=(SELECT value FROM sort WHERE id=@id) DESC, value ASC;
一切都很好,但不是自然的。通过上面的查询,我得到结果abc1, abc10, abc2, abc20, abc3
。我要查找的结果是 abc1, abc2, abc3, abc10, abc20
。当然,如果我更改@id=4,结果应该是abc10、abc20、abc1、abc2、abc3。
通过下面的查询,我得到了我想要的自然排序。
SELECT * FROM sort ORDER BY LENGTH(value), value;
所以问题是:如何将两个 ORDER BY 子句合并为一个?
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 abc1, 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这应该有效:
This should work: