在ORDER BY上使用IF语句

时间:2015-03-18 11:03:53

标签: mysql

表格结构

id int unsigned auto_increment
type int
value varchar

数据

id  type value
1   1   1000000
2   1   20000
3   1   25000
4   1   50000
5   1   25000
6   1   20000
7   1   20000
8   1   50000
9   1   20000
10  1   50000
11  1   50000
12  1   50000
13  1   200000
14  1   20000
15  1   25000
16  1   20000
17  1   25000
18  1   25000
19  1   20000
20  1   50
21  1   20000
22  1   50000
23  1   1000000
24  1   25000
25  1   25000
26  1   50000
27  1   50000
28  1   50000
29  2   a
30  2   b

表中有两种类型,如果type为1,则数字为number,如果type为2,则该值为string,因此,如果我想按值排序,我需要将值转换为UNSIGNED当type为1时,如果type为2,则按字母排序,这是我写的MySQL脚本。

SELECT *,
    CONVERT(`value`, UNSIGNED) `result`
FROM `tests`
ORDER BY IF(`result` = 0, `value`, `result`) DESC

我使用result = 0检查值是字符串还是数字,如果result = 0 ORDER BY value,如果不是ORDER BY CONVERT result,但输出不是正确的顺序如果我将代码编辑为

,请CONVERT result
SELECT *,
    CONVERT(`value`, UNSIGNED) `result`
FROM `tests`
ORDER BY IF(`result` = 0, `result`, `result`) DESC

输出是正确的,这意味着IF条件有效,但结果是错误的,不知道。

转储查询

CREATE TABLE IF NOT EXISTS `tests` (
  `id` int(10) unsigned NOT NULL,
  `type` int(11) DEFAULT '1',
  `value` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `tests` (`id`, `type`, `value`) VALUES
(1, 1, '1000000'),
(2, 1, '20000'),
(3, 1, '25000'),
(4, 1, '50000'),
(5, 1, '25000'),
(6, 1, '20000'),
(7, 1, '20000'),
(8, 1, '50000'),
(9, 1, '20000'),
(10, 1, '50000'),
(11, 1, '50000'),
(12, 1, '50000'),
(13, 1, '200000'),
(14, 1, '20000'),
(15, 1, '25000'),
(16, 1, '20000'),
(17, 1, '25000'),
(18, 1, '25000'),
(19, 1, '20000'),
(20, 1, '50'),
(21, 1, '20000'),
(22, 1, '50000'),
(23, 1, '1000000'),
(24, 1, '25000'),
(25, 1, '25000'),
(26, 1, '50000'),
(27, 1, '50000'),
(28, 1, '50000'),
(29, 2, 'a'),
(30, 2, 'b');

1 个答案:

答案 0 :(得分:2)

按顺序使用多个子句:

ORDER BY type,  -- put numbers first
         (case when type = 1 then value + 0 end) desc, -- convert values to numbers
         value

使用一个表达式(例如if()case)的问题是结果转换为一种类型。因此,您要对数字或字符串进行排序,但不能同时排序。