I've currently made a simple record table, with the recordID as the auto-increment primary key, the question is, due to religious reasons, my employer DOES NOT want to include the number 4 and 6 in the recordID, so instead of checking the recordID everytime after the record has been made, is there a much easier way to solve my current problem?
EDIT:
Here's a quick test table I've created based on Vanojx1's answer. So what did I do wrong?
CREATE TABLE `test` (
`ID` int(11) NOT NULL,
`value` int(11) NOT NULL
)
DELIMITER $$
CREATE TRIGGER `jump4and6` BEFORE INSERT ON `test` FOR EACH ROW BEGIN
SET #nextId = (SELECT MAX(`id`) FROM `test`);
IF (#nextId IN (4,6)) THEN
SET NEW.id = #nextId + 1;
SET #nextId = #nextId + 2;
ELSE
SET NEW.id = #nextId;
SET #nextId = #nextId + 1;
END IF;
INSERT INTO `test`(`id`) VALUES (#nextId);
END
$$
DELIMITER ;
ALTER TABLE `test` ADD PRIMARY KEY (`ID`);
ALTER TABLE `test` MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT;
Everything works so far, but when I tried to insert a row:
INSERT INTO `test`(value) VALUES (123456);
This happens.
#1442 - Can't update table 'test' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
You can create the primary key as an integer, then use a trigger before insert like this:
DELIMITER $$
CREATE TRIGGER jump4and6
BEFORE INSERT
ON your_table
FOR EACH ROW BEGIN
SET #nextId = (SELECT MAX(current_index) FROM your_table_sequence);
IF (#nextId IN (4,6)) THEN
SET NEW.id = #nextId + 1;
SET #nextId = #nextId + 2;
ELSE
SET NEW.id = #nextId;
SET #nextId = #nextId + 1;
END IF;
INSERT INTO your_table_sequence (current_index) VALUES (#nextId);
END$$
You also need a table to store your primary key sequence
Related
In my MySQL Database, I have a table with a composite primary key where the ID is not in auto_increment mode. Something like this :
CREATE TABLE table_a (
fk_table_b INT UNSIGNED NOT NULL,
id INT UNSIGNED,
label VARCHAR(80) NOT NULL,
PRIMARY KEY (fk_table_b, id),
FOREIGN KEY fk_table_b
REFERENCES table_b(id)
);
To increment the ID in function of the foreign key, I made a trigger like this :
DELIMITER $$
CREATE TRIGGER table_a_auto_increment
BEFORE INSERT ON table_a
FOR EACH ROW BEGIN
SET NEW.id = (
SELECT IFNULL(MAX(id), 0) + 1
FROM table_a
WHERE table_a.fk_table_b = NEW.fk_table_b
);
END $$
DELIMITER ;
But when I do SELECT LAST_INSERT_ID() I am getting 0 as the new id ... Normally you could override the LAST_INSERT_ID() by giving it a number like this :
INSERT table_a ( fk_table_b, id)
VALUES (1, LAST_INSERT_ID(5));
SELECT LAST_INSERT_ID(); -- -> it gives me 5
So I have tried to combine both to do this trigger :
DELIMITER $$
CREATE TRIGGER table_a_auto_increment
BEFORE INSERT ON table_a
FOR EACH ROW BEGIN
SET NEW.id = (
SELECT LAST_INSERT_ID(IFNULL(MAX(id), 0) + 1)
FROM table_a
WHERE table_a.fk_table_b = NEW.fk_table_b
);
END $$
DELIMITER ;
But it's still giving me 0 when I insert something in the base ... Do you know if there is a way to make it work ?
Thanks a lot.
-- EDIT 2020-08-14
Finally it seems impossible to override the LAST_INSERT_ID function inside the TRIGGER, so I changed my solution by removing the trigger and doing it inside my insert function like this :
INSERT table_a ( fk_table_b, id, label)
VALUES (1, LAST_INSERT_ID((
SELECT IFNULL(MAX(old_one.id), 0) + 1
FROM table_a AS old_one
WHERE old_one.fk_table_b = table_a.fk_table_b
)), "something");
And then, this is giving me the good result I can use in my backend :)
You may use additional service table:
CREATE TABLE service_table (id BIGINT AUTO_INCREMENT PRIMARY KEY);
and
DELIMITER $$
CREATE TRIGGER table_a_auto_increment
BEFORE INSERT ON table_a
FOR EACH ROW
BEGIN
SET NEW.id = (
SELECT IFNULL(MAX(id), 0) + 1
FROM table_a
WHERE table_a.fk_table_b = NEW.fk_table_b
);
DELETE FROM service_table WHERE id IS NOT NULL;
INSERT INTO service_table VALUES (NEW.id - 1);
INSERT INTO service_table VALUES (NULL);
SET NEW.id = LAST_INSERT_ID() - 1;
END $$
DELIMITER ;
fiddle (foreign key removed).
Maybe the code may be simplified a little - do it yourself.
Service table may be defined as Engine = MEMORY (if available).
The code is not safe for concurrent inserts.
I want only 6400 number of rows in my newtable. How do I do this?
I have a table that looks like this:
CREATE TABLE `newtable` (
ID_NT int(10) NOT NULL AUTO_INCREMENT
)ENGINE=InnoDB DEFAULT CHARSET=latin1;
You can use a trigger on your table. This works of course only if you don't delete rows
DELIMITER $$
CREATE TRIGGER InsertPreventTrigger BEFORE INSERT ON yourtable
FOR EACH ROW
BEGIN
DECLARE idcount INT;
set idcount = ( select count(*) from id where request = new.request );
IF idcount> 6400
THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'You can not insert record';
END $$
DELIMITER ;
And you have ti change yourtable and id ti fit to your needs
Updates to with count rows, that fits the request better
Challenge:
Create a method to set "auto_increment" values for tables in a non-sequential way.
The goal is to override the "auto_increment" mechanism and allow the function "LAST_INSERT_ID()" to continue working as expected (returning an INT), so that no changes are needed in software side.
My Solution
The method I found is based on an auxiliary table (unique_id), that stores values available to be assigned. Values are then selected randomly, and removed from the tables as used. When the table gets empty, a new set of ID's is created.
This example is working as expected, but with one problem.
Tables for the demo:
CREATE TABLE `unique_id` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=100;
CREATE TABLE `test_unique_id` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=1;
Defined a stored procedure and a function:
DELIMITER $$
DROP PROCEDURE IF EXISTS `UNIQUE_ID_REFILL`$$
CREATE PROCEDURE UNIQUE_ID_REFILL()
BEGIN
DECLARE a INT Default 0 ;
simple_loop: LOOP
SET a=a+1;
INSERT INTO unique_id (id) values(null);
IF a=100 THEN
LEAVE simple_loop;
END IF;
END LOOP simple_loop;
END $$
DROP FUNCTION IF EXISTS `UNIQUE_ID_GET`$$
CREATE FUNCTION UNIQUE_ID_GET()
RETURNS INT(11)
MODIFIES SQL DATA
BEGIN
DECLARE new_id INT(11);
DECLARE unique_id_count INT(11);
SET new_id = 0;
SELECT COUNT(*) INTO unique_id_count FROM unique_id;
IF unique_id_count=0 THEN
CALL UNIQUE_ID_REFILL();
END IF;
SELECT id INTO new_id FROM unique_id ORDER BY RAND() LIMIT 1;
DELETE FROM unique_id WHERE id = new_id;
RETURN new_id;
END $$
Created a Trigger on the destination table (test_unique_id):
CREATE TRIGGER test_unique_id__unique_id BEFORE INSERT ON test_unique_id
FOR EACH ROW
SET NEW.id = UNIQUE_ID_GET();
The solution is getting the random ID's as expected:
INSERT INTO test_unique_id(name) VALUES ('A'),('B'),('C');
Creates the rows:
id name
154 'A'
129 'B'
173 'C'
The Problem
The main problem is that LAST_INSERT_ID() stops working... and the software side is broken:
SELECT LAST_INSERT_ID();
0
Any ideas on how to solve this problem? or any other different approach to the challenge?
Thank you very much.
I am trying to create to trigger to divide my primary key into two groups.
Here is my table:
CREATE TABLE `q_locations` (
`id` int(11) NOT NULL,
`name` varchar(300) NOT NULL,
`standalone` bit(1) NOT NULL DEFAULT b'0',
UNIQUE KEY `id` (`id`),
KEY `standalone` (`standalone`)
)
If standalone is 0, id should start from 1, if standalone = 1, id should start from 1000. Id should be increment after each insert.
My trigger:
DELIMITER $$
CREATE TRIGGER trigger_insert_q_locations
BEFORE INSERT ON q_locations
FOR EACH ROW
BEGIN
SET New.id = (
SELECT coalesce(max(id) + 1, (case when standalone = 0 then 1 else 1000 end))
FROM q_locations
WHERE standalone = NEW.standalone);
END;
Update: So with help I got, I managed to insert trigger without no errors, bu when I update my locations table, trigger doesn't do anything. Values just keep incrementing as default.
Try:
SET NEW.id = (SELECT coalesce(...) ...)
Maybe SELECT INTO isn't working properly in Update Triggers with NEW-Aliases.
UPDATE:
This should work:
DELIMITER $$
CREATE TRIGGER trigger_insert_q_locations
BEFORE INSERT ON q_locations
FOR EACH ROW
BEGIN
DECLARE currentid INT;
SET currentid = (SELECT max(id) FROM q_locations WHERE standalone = NEW.standalone);
IF NEW.standalone = 0 THEN
SET NEW.id = coalesce(currentid + 1, 1);
ELSE
SET NEW.id = coalesce(currentid + 1,1000);
END IF;
END;
I would like to auto_increment two different tables in a single mysql database, the first by multiples of 1 and the other by 5 is this possible using the auto_increment feature as I seem to only be able to set auto_increment_increment globally.
If auto_increment_increment is not an option what is the best way to replicate this
Updated version: only a single id field is used. This is very probably not atomic, so use inside a transaction if you need concurrency:
http://sqlfiddle.com/#!2/a4ed8/1
CREATE TABLE IF NOT EXISTS person (
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY ( id )
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
CREATE TRIGGER insert_kangaroo_id BEFORE INSERT ON person FOR EACH ROW BEGIN
DECLARE newid INT;
SET newid = (SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'person'
);
IF NEW.id AND NEW.id >= newid THEN
SET newid = NEW.id;
END IF;
SET NEW.id = 5 * CEILING( newid / 5 );
END;
Old, non working "solution" (the before insert trigger can't see the current auto increment value):
http://sqlfiddle.com/#!2/f4f9a/1
CREATE TABLE IF NOT EXISTS person (
secretid INT NOT NULL AUTO_INCREMENT,
id INT NOT NULL,
PRIMARY KEY ( secretid )
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
CREATE TRIGGER update_kangaroo_id BEFORE UPDATE ON person FOR EACH ROW BEGIN
SET NEW.id = NEW.secretid * 5;
END;
CREATE TRIGGER insert_kangaroo_id BEFORE INSERT ON person FOR EACH ROW BEGIN
SET NEW.id = NEW.secretid * 5; -- NEW.secretid is empty = unusuable!
END;