开发者

Default value for enum when assigned a value not in the enumeration

Is there a way in MySQL table to assign a default when a value that is not in the enumeration is assigned to that field?

CREATE TABLE `comments` (
  `status` enum('approved','moderated','unmoderated') NOT NULL DEFAULT 'unmoderated'
);

Works if status is not defined at creation, but if you set it to something not in the enumeration or NULL, it is "blanked" (doesn't seem to be NULL). I wo开发者_JS百科uld expect it to be 'unmoderated' if I set it to NULL, since it can't be null. Not sure if that makes sense. Do I need to sanitize my data before inserting to make sure the value exists in the enumeration first?

UPDATE comments SET status = NULL;
UPDATE comments SET status = 'not_in_there';


If you try and set an ENUM field to a value not in the definition list then it will be inserted as index 0, an empty string. The default only comes into play if no value is specified for that column.

I guess to do what you need you will need to check for an invalid value in the code first and then include the value you want in the query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜