How to generate/autoincrement guid on insert without triggers and manual inserts in mysql?

冷暖自知 提交于 2021-02-04 20:56:05

问题


Im revisiting my database and noticed I had some primary keys that were of type INT.

This wasn't unique enough so I thought I would have a guid. I come from a microsoft sql background and in the ssms you can choose type to "uniqeidentifier" and auto increment it.

In mysql however Ive found that you have to make triggers that execute on insert for the tables you want to generate a guide id for. Example:

Table:

CREATE TABLE `tbl_test` (
  `GUID` char(40) NOT NULL,
  `Name` varchar(50) NOT NULL,
  PRIMARY KEY (`GUID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Trigger:

CREATE TRIGGER `t_GUID` BEFORE INSERT ON `tbl_test`
 FOR EACH ROW begin
 SET new.GUID = uuid();

Alternatively you have to insert the guid yourself in the backend.

Im no DB expert but still remember that triggers cause performance problems.

The above is something I found here and is 9 years old so I was hoping something has changed?


回答1:


As far as stated in the documentation, you can use uid() as a column default starting version 8.0.13, so something like this should work:

create table tbl_test (
    guid binary(16) default (uuid_to_bin(uuid())) not null primary key,
    name varchar(50) not null
);

This is pretty much copied from the documentation. I don't have a recent enough version of MySQL at hand to test this.




回答2:


You can make a

INSERT INTO  `tbl_test` VALUES  (uuid(),'testname');

This would generate a new uuid, when you call it.

Or you can also use the modern uuid v4 by using one of these functions instead of the standard uuid(), which is more random than the uuid in mysql

How to generate a UUIDv4 in MySQL?

You can use since 8.0.13

CREATE TABLE t1 (
    uuid_field     VARCHAR(40) DEFAULT (uuid())
);

But you wanted more than unique, but here are only allowed internal functions and not user defined as for uuid v4, for that uyou need the trogger



来源:https://stackoverflow.com/questions/61349754/how-to-generate-autoincrement-guid-on-insert-without-triggers-and-manual-inserts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!