MySQL to achieve sequence effect
Generally, sequence is used to process primary key fields. There is no sequence in mysql, but MySQL provides an increment to achieve similar purposes, but it is only an increment, and cannot set step size, start index, cycle, etc. the most important thing is that a table can only be used by one field, but sometimes we need two or more fields To realize auto increment (single table and multi field auto increment), MySQL itself can't realize it, but we can use to create a sequence table and use functions to obtain the sequence values
1. Create a new sequence table
- drop table if exists sequence;
- create table sequence (
- seq_name VARCHAR(50) NOT NULL, -- Sequence name
- current_val INT NOT NULL, -- Current value
- increment_val INT NOT NULL DEFAULT 1, -- step(span)
- PRIMARY KEY (seq_name) );
2. Add a sequence
- INSERT INTO sequence VALUES ('seq_test1_num1', '0', '1');
- INSERT INTO sequence VALUES ('seq_test1_num2', '0', '2');
3. Create a function to get the current value of the sequence (the value of the V ﹣ SEQ ﹣ name parameter represents the sequence name)
- create function currval(v_seq_name VARCHAR(50))
- returns integer
- begin
- declare value integer;
- set value = 0;
- select current_val into value from sequence where seq_name = v_seq_name;
- return value;
- end;
4. Query the current value
- select currval('seq_test1_num1');
5. Create a function to get the next value of the sequence (the value of the V ﹣ SEQ ﹣ name parameter represents the sequence name)
- create function nextval (v_seq_name VARCHAR(50))
- returns integer
- begin
- update sequence set current_val = current_val + increment_val where seq_name = v_seq_name;
- return currval(v_seq_name);
- end;
6. Query next value
- select nextval('seq_test1_num1');
7. create a new table for testing
- DROP TABLE IF EXISTS `test1`;
- CREATE TABLE `test1` (
- `name` varchar(255) NOT NULL,
- `value` double(255,0) DEFAULT NULL,
- `num1` int(11) DEFAULT NULL,
- `num2` int(11) DEFAULT NULL,
- PRIMARY KEY (`name`)
- );
8. Before inserting a new record into a new trigger, assign a value to the auto increment field to achieve the auto increment effect
- CREATE TRIGGER `TRI_test1_num1` BEFORE INSERT ON `test1` FOR EACH ROW BEGIN
- set NEW.num1 = nextval('seq_test1_num1');
- set NEW.num2 = nextval('seq_test1_num2');
- END
9. Final test of self increasing effect
- INSERT INTO test1 (name, value) VALUES ('1', '111');
- INSERT INTO test1 (name, value) VALUES ('2', '222');
- INSERT INTO test1 (name, value) VALUES ('3', '333');
- INSERT INTO test1 (name, value) VALUES ('4', '444');
10. Results display
- SELECT * FROM test1;