MySQL ORDER BY returns 可变长度字符串的错误结果

MySQL ORDER BY returns incorrect results for variable length strings

我有一个 table 这样的:

CREATE TABLE IF NOT EXISTS `tags` (
  `tid` int(11) NOT NULL,
  `name` varchar(25) NOT NULL,
  `type` enum('spec','gen','cat','app','ep') DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `tags` ADD PRIMARY KEY (`tid`);
ALTER TABLE `tags` MODIFY `tid` int(11) NOT NULL AUTO_INCREMENT;

╔═════╤═══════════════════════╤════════╗
║ <strong>tid</strong> │ name                  │ type   ║
╟─────┼───────────────────────┼────────╢
║   <strong>1</strong> │ "spike"               │ <em>NULL</em>   ║
║   <strong>2</strong> │ "gala dress"          │ 'app'  ║
║   <strong>3</strong> │ "s1e1"                │ 'ep'   ║
║   <strong>4</strong> │ "dragon"              │ 'spec' ║
║   <strong>5</strong> │ "backgroud character" │ 'cat'  ║
║   <strong>6</strong> │ "s1e2"                │ 'ep'   ║
║   <strong>7</strong> │ "male"                │ 'gen'  ║
║   <strong>8</strong> │ "s1e3"                │ 'ep'   ║
║   <strong>9</strong> │ "main six"            │ 'cat'  ║
╚═════╧═══════════════════════╧════════╝

运行 以下查询:

SELECT DISTINCT type FROM `tags` ORDER BY type DESC

结果不是我所期望的,ep排在最前面,而它应该排在cat之后:

╔════════╗
║ type   ║
╟────────╢
║ 'ep'   ║
║ 'app'  ║
║ 'cat'  ║
║ 'gen'  ║
║ 'spec' ║
║ <em>NULL</em>   ║
╚════════╝

我认为这是因为 'ep' 比其余项目短,但我如何才能对 table 进行排序,而不会将较短的字符串排在较长的字符串之前?

在这种特定情况下,我 可以 使用每个字符串中的第一个字符进行排序,但我想要一个面向未来的解决方案,以防 2 种类型以相同的字母开头(s) 稍后。

您的字段是 enum,并且 mysql 按内部索引值排序:

`type` enum('spec','gen','cat','app','ep') DEFAULT NULL
             0       1     3     4     5

当您对 desc 进行排序时,ep 排在第一位,因为它具有最高索引值。