我有一个按column
排序的查询:
select * from mytable order by column asc — sort table
column
类型为varchar,因此输出为:
1
10
100
11
12
13
如果我希望它们按数值排序,我应如何排序,因此输出为:
1
10
11
12
13
100
答案 0 :(得分:45)
使用:
order by cast(column as unsigned) asc
答案 1 :(得分:22)
如果您希望仅将column
视为INT
,则可以使用此功能:
SELECT * FROM mytable ORDER BY column+0;
1
10
11
12
13
100
或者,如果您想将column
同时视为INT
和VARCHAR
SELECT * FROM mytable ORDER BY column+0, column; #this will sort the column by VARCHAR first and then sort it by INT
abc
xyz
1
10
11
12
13
100
答案 2 :(得分:11)
这也应该有效:
order by (0 + column) asc
答案 3 :(得分:6)
如果我们只是稍微通过声明修改顺序(在按字段的顺序中添加“+0”),您可以强制MySQL自然地对字段进行排序。
> select * from mytable order by column+0 asc;
column
1
10
11
12
13
100
答案 4 :(得分:3)
Added a full code script here , but need to sort 1001 and 1002 before - as well.
We have total 5 solution , means 5 different queries as solution with full script.
=============================================================
SET NAMES utf8;
SET foreign_key_checks = 0;
SET time_zone = 'SYSTEM';
SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';
DROP TABLE IF EXISTS `varchar_sort`;
CREATE TABLE `varchar_sort` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`actual_user_id` varchar(200) DEFAULT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `varchar_sort` (`user_id`, `actual_user_id`) VALUES
(1, '1001-4'),
(2, '1001-1'),
(3, '1001-111'),
(4, '1002-1'),
(5, '1001-66'),
(6, '1001-100'),
(7, '1001-110');
SELECT user_id,actual_user_id,CONVERT(SUBSTRING_INDEX(actual_user_id,'-',-1),UNSIGNED INTEGER) AS num
FROM varchar_sort
ORDER BY num;
SELECT user_id,actual_user_id
FROM varchar_sort
ORDER BY CONVERT(SUBSTRING(actual_user_id, 6), SIGNED INTEGER);
SELECT user_id,actual_user_id
FROM varchar_sort
ORDER BY CONVERT(SUBSTRING(actual_user_id, LOCATE('-', actual_user_id) + 1), SIGNED INTEGER);
SELECT *, CAST(SUBSTRING_INDEX(actual_user_id, '-', -1) AS UNSIGNED) as num FROM varchar_sort ORDER BY num;
通过转换(替换(actual_user_id,' - ',''),SIGNED INTEGER)选择*来自varchar_sort顺序
**Need to sort 1001 and 1002 as well.**