MySQL设置默认ID UUID [英] MySQL set default id UUID
问题描述
我正在尝试在具有id
字段的数据库中创建表,默认情况下将使用UUID填充ID.
I'm trying to create tables in a database that has an id
field that will populate the id with an UUID by default.
我尝试过类似的事情:
CREATE TABLE FOO (
id CHAR(36) PRIMARY KEY DEFAULT uuid()
);
非常感谢您的协助.
推荐答案
从5.7开始,MySQL不支持使用函数作为列的默认值.
MySQL as of 5.7 does not support using a function as the default value of a column.
数据类型规范中的DEFAULT value子句指示列的默认值.除了一个例外,默认值必须为常数;否则为0. 它不能是函数或表达式.
https://dev.mysql.com/doc/refman/5.7/zh-CN/data-type-defaults.html
另一种选择是使用触发器来监视所需表的BEFORE INSERT
.
The alternative would be to use a trigger to monitor the BEFORE INSERT
of the desired table.
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()
值.
This will change the default value of an INSERT
statement to the uuid()
value, unless it has been explicitly defined.
这篇关于MySQL设置默认ID UUID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!