How to set the type of primary key to UUID in mysql table

Today I found a problem in changing someone else’s code, to create a uuid type primary key

CREATE TABLE `product` (
  `id` VARCHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',
  `productNum` VARCHAR(50) NOT NULL,
  `productName` VARCHAR(50) DEFAULT NULL,
  `cityName` VARCHAR(50) DEFAULT NULL,
  `DepartureTime` TIMESTAMP NULL DEFAULT NULL,
  `productPrice` DECIMAL(10,0) DEFAULT NULL,
  `productDesc` VARCHAR(255) DEFAULT NULL,
  `productStatus` INT(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

I want to change the id in the product in the above table to uuid type

uuid

   UUID means Universally Unique Identifier (Universally Unique Identifier). The uuid project application www.1b23.com refers to a number generated on a machine, which guarantees that it is unique to all machines in the same time and space. Usually the platform will provide the generated API. In other words, the uniqueness of the primary key id can be guaranteed within a certain range. The
   uuid() function can be used directly in mysql to generate a random uuid. The
   normal uuid is 36 bits long, for example: d48644cc-2c7a-4714-9900-18ab99e80b03 , Among which 4 characters are "-", you can use the replace() function to replace "-" in mysql

replace function

The uuid generated by default contains'-', we can use the replace function to replace the'-', the SQL is as follows:

select replace(uuid(),"-","") as uuid;

Baidu later found that this operation can be achieved through triggers

Create a trigger on the left side
Insert picture description here
named id_trigger.
Below is the trigger code

DELIMITER $$

CREATE
    /*[DEFINER = { user | CURRENT_USER }]*/
    TRIGGER `ssm_project1`.`id_trigger` BEFORE INSERT
    ON `ssm_project1`.`product`
    FOR EACH ROW BEGIN
		SET new.id=REPLACE(UUID(),'-','');
    END$$

DELIMITER ;

The trigger realizes that a unique uuid is generated when the data is inserted and the
project is successfully solved after running the project.
Insert picture description here

Guess you like

Origin blog.csdn.net/he1234555/article/details/114012854