我有它的表定义:
CREATE TABLE `table2` (
`id` INT NOT NULL,
`varchardata` VARCHAR(45) NULL,
`intdata` INT(10) NULL,
PRIMARY KEY (`id`));
数据:
INSERT INTO `table2` (`id`, `varchardata`, `intdata`) VALUES ('1', '12', '12');
INSERT INTO `table2` (`id`, `varchardata`, `intdata`) VALUES ('2', 'keyur', '7');
INSERT INTO `table2` (`id`, `varchardata`, `intdata`) VALUES ('3', '3', '3');
INSERT INTO `table2` (`id`, `varchardata`, `intdata`) VALUES ('4', '13', '13');
INSERT INTO `table2` (`id`, `varchardata`, `intdata`) VALUES ('5', '6', '6');
当我执行查询时:
SELECT * FROM table2 order by intdata asc;
它给出了结果:
是否可以按照某种顺序对数据进行排序,并将o / p作为
3
6
12
13
keyur
这是varchar数据,所以我完全不知道该怎么做,或者它实际上是否可能? 那么建议那可能吗?
答案 0 :(得分:2)
另一种方法是正确处理0
(将其与非数字值区分开来)
SELECT id, varchardata, intdata
FROM
(
SELECT id, varchardata, intdata, varchardata REGEXP '[0-9]' is_numeric
FROM table2
) q
ORDER BY is_numeric DESC, 1 * varchardata
输出:
| ID | VARCHARDATA | INTDATA | |----|-------------|---------| | 3 | 3 | 3 | | 5 | 6 | 6 | | 1 | 12 | 12 | | 4 | 13 | 13 | | 2 | keyur | 7 |
这是 SQLFiddle 演示
答案 1 :(得分:0)
你的intdata包含varchar - 有一个字母数字排序
SELECT *
FROM table2
ORDER BY CAST(intdata as int) asc;
答案 2 :(得分:0)
试试这个:
SELECT *
FROM table2
ORDER BY IF(CAST(varchardata AS SIGNED) = 0, 99999, CAST(varchardata AS SIGNED));
<强>输出强>
| ID | VARCHARDATA | INTDATA |
|----|-------------|---------|
| 8 | 3 | 3 |
| 10 | 6 | 6 |
| 6 | 12 | 12 |
| 9 | 13 | 13 |
| 7 | keyur | 7 |