フィールド 'noticeBy' enum('email','mobile','all','auto','nothing') NOT NULL DEFAULT 'auto' があります。知られているように、ENUM フィールドによる順序付けは、そのインデックスに対して相対的に実行されます。しかし、どうすればその値で注文できるのでしょうか?
5 に答える
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'
forENUM('b', 'a')
. The empty string sorts before nonempty strings, andNULL
values sort before all other enumeration values.To prevent unexpected results when using the
ORDER BY
clause on anENUM
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)
orORDER 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)
これも機能します:
ORDER BY FIELD(noticeBy, 'all','auto','email','mobile','nothing')
(これを達成するための設定があるとは思いません。ソート値を指定する必要があります。)
順序は自由に定義できます。
ORDER BY CASE noticeBy
WHEN 'email' THEN 1
WHEN 'mobile' THEN 2
WHEN 'all' THEN 3
WHEN 'auto' THEN 4
ELSE 5
END
これにより、次の順序で行が返されます: 電子メール、モバイル、すべて、自動、なし。