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

前端 未结 2 1310
花落未央
花落未央 2021-01-15 00:59

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 mic

相关标签:
2条回答
  • 2021-01-15 01:30

    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

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题