gpt4 book ai didi

mysql - 主键 UUID 触发器

转载 作者:行者123 更新时间:2023-11-28 23:19:24 25 4
gpt4 key购买 nike

我正在尝试创建一个表,其中主键是每次出现 INSERT 事件时自动生成的 UUID。但问题是当我尝试执行 INSERT 查询时跳过主键列,如下所示:

INSERT INTO `tablename` (`reference`) VALUES ('hey');

没有插入行,也没有错误。只是“插入 0 行...”这是我的 table 和触发器。谢谢。

CREATE TABLE `tablename` (
`uuid` char(36) NULL,
`reference` varchar(100) NOT NULL,
PRIMARY KEY (uuid)
);

DELIMITER ;;
CREATE TRIGGER before_insert_tablename
BEFORE INSERT ON tablename
FOR EACH ROW
BEGIN
IF new.uuid IS NULL THEN
SET new.uuid = uuid();
END IF;
END
;;

DELIMITER ;

最佳答案

不能主键设置为NULL

只需将其更改为NOT NULL

`uuid` char(36) NOT NULL,

The primary key for a table represents the column or set of columns that you use in your most vital queries. It has an associated index, for fast query performance. Query performance benefits from the NOT NULL optimization, because it cannot include any NULL values.

Reference

关于mysql - 主键 UUID 触发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42477600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com