我正在尝试在具有 id
字段的数据库中创建表,默认情况下该字段将使用 UUID 填充 id。
我试过类似的方法:
CREATE TABLE FOO (
id CHAR(36) PRIMARY KEY DEFAULT uuid()
);
非常感谢您的帮助。
最佳答案
MySQL 5.7、8.0.12 及更早版本
MySQL 5.7 或 8.0.12 不支持使用函数或表达式作为列的默认值。
The DEFAULT value clause in a data type specification indicates a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression.
https://dev.mysql.com/doc/refman/5.7/en/data-type-defaults.html
另一种方法是使用触发器来监视所需表的 BEFORE INSERT
。
DELIMITER ;;
CREATE TRIGGER `foo_before_insert`
BEFORE INSERT ON `foo` FOR EACH ROW
BEGIN
IF new.id IS NULL THEN
SET new.id = uuid();
END IF;
END;;
DELIMITER ;
这会将 INSERT
语句的默认值更改为 uuid()
值,除非已明确定义。
MySQL 8.0.13 及更新版本
随着release of MySQL 8.0.13一个表达式现在可以用作默认值,前提是它被括在括号中。
示例 db<>fiddle
The default value specified in a
DEFAULT
clause can be a literal constant or an expression. With one exception, enclose expression default values within parentheses to distinguish them from literal constant default values. The exception is that, forTIMESTAMP
andDATETIME
columns, you can specify theCURRENT_TIMESTAMP
[constant] as the default, without enclosing parentheses.CREATE TABLE foo (b BINARY(16) DEFAULT (UUID_TO_BIN(UUID())));
When inserting a new row, the default value for a column with an expression default can be inserted either by omitting the column name or by specifying the column as
DEFAULT
(just as for columns with literal defaults):INSERT INTO foo () VALUES(); INSERT INTO foo () VALUES(DEFAULT);
https://dev.mysql.com/doc/refman/8.0/en/data-type-defaults.html
关于MySQL设置默认ID UUID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46134550/