48

フィールド 'noticeBy' enum('email','mobile','all','auto','nothing') NOT NULL DEFAULT 'auto' があります。知られているように、ENUM フィールドによる順序付けは、そのインデックスに対して相対的に実行されます。しかし、どうすればその値で注文できるのでしょうか?

4

5 に答える 5

72

As documented under Sorting:

ENUM values are sorted based on their index numbers, which depend on the order in which the enumeration members were listed in the column specification. For example, 'b' sorts before 'a' for ENUM('b', 'a'). The empty string sorts before nonempty strings, and NULL values sort before all other enumeration values.

To prevent unexpected results when using the ORDER BY clause on an ENUM column, use one of these techniques:

  • Specify the ENUM list in alphabetic order.

  • Make sure that the column is sorted lexically rather than by index number by coding ORDER BY CAST(col AS CHAR) or ORDER BY CONCAT(col).

Per the second bullet, you can therefore sort on the column after it has been cast to a string:

ORDER BY CAST(noticeBy AS CHAR)
于 2013-07-11T22:02:16.117 に答える
68

これも機能します:

ORDER BY FIELD(noticeBy, 'all','auto','email','mobile','nothing')

(これを達成するための設定があるとは思いません。ソート値を指定する必要があります。)

于 2013-07-11T21:42:58.587 に答える
24

順序は自由に定義できます。

ORDER BY CASE noticeBy
           WHEN 'email' THEN 1
           WHEN 'mobile' THEN 2
           WHEN 'all' THEN 3
           WHEN 'auto' THEN 4
           ELSE 5
         END

これにより、次の順序で行が返されます: 電子メール、モバイル、すべて、自動、なし。

于 2013-07-11T21:40:14.593 に答える