Primary key UUID Trigger - mysql

I am trying to make a table where the primary key is auto generated UUID every time there's an INSERT event. But the problem is when I try to execute an INSERT query skipping the primary key column like this:
INSERT INTO `tablename` (`reference`) VALUES ('hey');
No row is inserted and no errors. Just "0 rows inserted..."
Here's my table and the trigger. Thank you.
CREATE TABLE `tablename` (
`uuid` char(36) NULL,
`reference` varchar(100) NOT NULL,
PRIMARY KEY (uuid)
);
DELIMITER ;;
CREATE TRIGGER before_insert_tablename
BEFORE INSERT ON tablename
FOR EACH ROW
BEGIN
IF new.uuid IS NULL THEN
SET new.uuid = uuid();
END IF;
END
;;
DELIMITER ;

You CAN NOT make a Primary key as NULL
Just change it to NOT NULL
`uuid` char(36) NOT NULL,
The primary key for a table represents the column or set of columns that you use in your most vital queries. It has an associated index, for fast query performance. Query performance benefits from the NOT NULL optimization, because it cannot include any NULL values.
Reference

Related

get Subquery returns more than 1 row error when use auto_increment in MySQL trigger

I create two tables sequence and sequence_test,the definitions are follows:
create table sequence
(
id bigint unsigned auto_increment comment 'id'
primary key
)comment 'sequence' collate = utf8mb4_unicode_ci;
create table sequence_test
(
id bigint unsigned auto_increment comment 'id'
primary key,
se_id bigint unsigned not null comment 'trigger'
)
comment 'test' collate = utf8mb4_unicode_ci;
then I create a MySQL trigger to generate the se_id value when insert row into sequence_test table ,the trigger definition:
create trigger id_generator
before insert
on sequence_test for each row
begin
if new.se_id is null then
insert into sequence value ();
set new.se_id=(select last_insert_id() from sequence);
end if;
end;
then when I insert table, I get error like [21000][1242] Subquery returns more than 1 row,and why?
I have known the answer, here
set new.se_id=(select last_insert_id() from sequence);
use
set new.se_id=last_insert_id()
last_insert_id() will return the last insert value

Specific field parameter when creating a table MySQL

I'm using MySQL Workbench.
I would like to create a table named courseInfo and I want to put a column named moduleCode in it, but I want it to always be similar in format: CFSM H0000 where the four zeros are a number that increases starting with 0000.
For example:
CFSM H0001
CFSM H0002
[..]
You cannot auto-increment character type columns in MySQL, as auto-increment is only possible on integer type columns. One (alphanumeric) auto-incrementing moduleCode column would therefore not be possible. However, you could try splitting up the moduleCode into two columns, for example like so:
CREATE TABLE `courseInfo` (
`prefix` CHAR(6) NOT NULL DEFAULT 'CFSM H',
`id` SMALLINT(4) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
KEY (`id`)
) AUTO_INCREMENT = 0;
Where prefix could for example be "CFSM H" and id could be 0001
Then, upon executing SELECT statements, you could merge the prefix column with the id column into a moduleCode column with CONCAT, e.g.:
SELECT CONCAT(`prefix`, `id`) as `moduleCode` FROM `courseInfo`;
An alternative approach (from MySQL version 5.7 and up) seems to be the use of a generated column, for example:
CREATE TABLE `courseInfo` (
`prefix` CHAR(6) NOT NULL DEFAULT 'CFSM H',
`id` SMALLINT(4) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
`moduleCode` CHAR(10) AS (CONCAT(`prefix`, `id`)),
KEY (`id`)
) AUTO_INCREMENT = 0;
However, the above example of a generated column would not work, because moduleCode is dependent on an auto-increment column, and the auto-increment is not executed yet at the time the generated column is computed. See also: https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html. It would throw an ER_GENERATED_COLUMN_REF_AUTO_INC error.
You could therefore use the first solution, or try to add moduleCode as a column and use an AFTER INSERT trigger to update its value:
CREATE TABLE `courseInfo` (
`prefix` CHAR(6) NOT NULL DEFAULT 'CFSM H',
`id` SMALLINT(4) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
`moduleCode` CHAR(10),
KEY (`id`),
UNIQUE KEY `unique_index` (`prefix`,`id`)
) AUTO_INCREMENT = 0;
DELIMITER //
CREATE TRIGGER `addModuleCode` AFTER INSERT ON `courseInfo`
FOR EACH ROW
BEGIN
UPDATE `courseInfo` SET `moduleCode` = CONCAT(NEW.`prefix`, NEW.`id`) WHERE `prefix` = NEW.`prefix` AND `id` = NEW.`id`;
END;//
DELIMITER ;

MySQL: Integrity error when inserting into database

So, I have this one column in my table that gets filled by a trigger when a new entry is inserted.
CREATE TABLE `users` (
`idusers` int(11) NOT NULL AUTO_INCREMENT,
`uid` char(64) DEFAULT NULL,
`uname` varchar(80) NOT NULL,
`password` char(128) NOT NULL,
`mail` varchar(120) NOT NULL,
PRIMARY KEY (`idusers`),
UNIQUE KEY `uname_UNIQUE` (`uname`),
UNIQUE KEY `mail_UNIQUE` (`mail`),
UNIQUE KEY `uid_UNIQUE` (`uid`)
);
DELIMITER $$
TRIGGER `flask`.`users_BEFORE_INSERT` BEFORE INSERT ON `users` FOR EACH ROW
BEGIN
set new.uid = sha2(new.idusers, 256);
END$$
DELIMITER ;
The problem now is that when I try to add a new row (only have a test one yet because of the error), in the trigger the value of new.idusers is somehow always 0 instead of the current auto_increment value.
What do I need to change in my trigger code so that the value used for generating the uid is the actual id and not always 0?
Since idusers is an AUTO_INCREMENT field, its value is known only after the record is inserted in the table.
Use an AFTER INSERT trigger instead of a BEFORE INSERT trigger, and update the newly inserted record:
DELIMITER $$
CREATE TRIGGER `flask`.`users_AFTER_INSERT` AFTER INSERT ON `users` FOR EACH ROW
BEGIN
UPDATE users SET uid = sha2(NEW.idusers, 256) WHERE idusers = NEW.idusers;
END $$
DELIMITER ;

Defining Composite Key with Auto Increment in MySQL

Scenario:
I have a table which references two foreign keys, and for each unique combination of these foreign keys, has its own auto_increment column. I need to implement a Composite Key that will help identify the row as unique using combination of these three (one foreign keys and one auto_increment column, and one other column with non-unique values)
Table:
CREATE TABLE `issue_log` (
`sr_no` INT NOT NULL AUTO_INCREMENT ,
`app_id` INT NOT NULL ,
`test_id` INT NOT NULL ,
`issue_name` VARCHAR(255) NOT NULL ,
primary key (app_id, test_id,sr_no)
);
Of course, there has to be something wrong with my query, because of which the error thrown is:
ERROR 1075: Incorrect table definition; there can be only one auto
column and it must be defined as a key
What I am trying to achieve:
I have an Application Table (with app_id as its primary key), each Application has a set of Issues to be resolved, and each Application has multiple number of tests (so the test_id col)
The sr_no col should increment for unique app_id and test_id.
i.e. The data in table should look like:
The database engine is InnoDB.
I want to achieve this with as much simplicity as possible (i.e. avoid triggers/procedures if possible - which was suggested for similar cases on other Questions).
You can't have MySQL do this for you automatically for InnoDB tables - you would need to use a trigger or procedure, or user another DB engine such as MyISAM. Auto incrementing can only be done for a single primary key.
Something like the following should work
DELIMITER $$
CREATE TRIGGER xxx BEFORE INSERT ON issue_log
FOR EACH ROW BEGIN
SET NEW.sr_no = (
SELECT IFNULL(MAX(sr_no), 0) + 1
FROM issue_log
WHERE app_id = NEW.app_id
AND test_id = NEW.test_id
);
END $$
DELIMITER ;
You can do this with myISAM and BDB engines. InnoDB does not support this. Quote from MySQL 5.0 Reference Manual.
For MyISAM and BDB tables you can specify AUTO_INCREMENT on a secondary column in a multiple-column index. In this case, the generated value for the AUTO_INCREMENT column is calculated as MAX(auto_increment_column) + 1 WHERE prefix=given-prefix.
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
I don't fully understand your increment requirement on the test_id column, but if you want an ~autoincrement sequence that restarts on every unique combination of (app_id, test_id), you can do an INSERT ... SELECT FROM the same table, like so:
mysql> INSERT INTO `issue_log` (`sr_no`, `app_id`, `test_id`, `issue_name`) SELECT
IFNULL(MAX(`sr_no`), 0) + 1 /* next sequence number */,
3 /* desired app_id */,
1 /* desired test_id */,
'Name of new row'
FROM `issue_log` /* specify the table name as well */
WHERE `app_id` = 3 AND `test_id` = 1 /* same values as in inserted columns */
This assumes a table definition with no declared AUTO_INCREMENT column. You're essentially emulating autoincrement behavior with the IFNULL(MAX()) + 1 clause, but the manual emulation works on arbitrary columns, unlike the built-in autoincrement.
Note that the INSERT ... SELECT being a single query ensures atomicity of the operation. InnoDB will gap-lock the appropriate index, and many concurrent processes can execute this kind of query while still producing non-conflicting sequences.
You can use a unique composite key for sr_no,app_id & test_id. You cannot use incremental in sr_no as this is not unique.
CREATE TABLE IF NOT EXISTS `issue_log` (
`sr_no` int(11) NOT NULL,
`app_id` int(11) NOT NULL,
`test_id` int(11) NOT NULL,
`issue_name` varchar(255) NOT NULL,
UNIQUE KEY `app_id` (`app_id`,`test_id`,`sr_no`)
) ENGINE=InnoDB ;
I have commented out unique constraint violation in sql fiddle to demonstrate (remove # in line 22 of schema and rebuild schema )
This is what I wanted
id tenant
1 1
2 1
3 1
1 2
2 2
3 2
1 3
2 3
3 3
My current table definition is
CREATE TABLE `test_trigger` (
`id` BIGINT NOT NULL,
`tenant` varchar(255) NOT NULL,
PRIMARY KEY (`id`,`tenant`)
);
I created one table for storing the current id for each tenant.
CREATE TABLE `get_val` (
`tenant` varchar(255) NOT NULL,
`next_val` int NOT NULL,
PRIMARY KEY (`tenant`,`next_val`)
) ENGINE=InnoDB ;
Then I created this trigger which solve my problem
DELIMITER $$
CREATE TRIGGER trigger_name
BEFORE INSERT
ON test_trigger
FOR EACH ROW
BEGIN
UPDATE get_val SET next_val = next_val + 1 WHERE tenant = new.tenant;
set new.id = (select next_val from get_val where tenant=new.tenant);
END$$
DELIMITER ;
This approach will be thread safe also because any insertion for the same tenant will happen sequentially because of the update query in the trigger and for different tenants insertions will happen parallelly.
Just add key(sr_no) on auto-increment column:
CREATE TABLE `issue_log` (
`sr_no` INT NOT NULL AUTO_INCREMENT ,
`app_id` INT NOT NULL ,
`test_id` INT NOT NULL ,
`issue_name` VARCHAR(255) NOT NULL ,
primary key (app_id, test_id,sr_no),
key (`sr_no`)
);
Why don't you try to change the position of declare fields as primary key, since when you use "auto_increment" it has to be referenced as the first. Like in the following example
CREATE TABLE `issue_log` (
`sr_no` INT NOT NULL AUTO_INCREMENT ,
`app_id` INT NOT NULL ,
`test_id` INT NOT NULL ,
`issue_name` VARCHAR(255) NOT NULL ,
primary key (sr_no,app_id, test_id)
);

mysql how to update a foreign key automatically

this is my tables
CREATE TABLE IF NOT EXISTS `carslibrary` (
`CarID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`CarName` varchar(255) NOT NULL,
PRIMARY KEY (`CarID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
CREATE TABLE IF NOT EXISTS `colorslibrary` (
`ColorID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`ColorName` varchar(255) NOT NULL,
PRIMARY KEY (`ColorID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
CREATE TABLE IF NOT EXISTS `facerecord` (
`carslibrary_ID` int(10) unsigned NOT NULL,
`colorslibrary_ID` int(11) unsigned NOT NULL,
KEY `carslibrary_ID` (`carslibrary_ID`),
KEY `colorslibrary_ID` (`colorslibrary_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
i noticed carslibrary_ID attribute inside facerecord table is not automatically updated when i add a car record inside carslibrary table, what should i do to be able to?
Firstly, you'll need to have a default value specified for the facerecord.colorslibrary_ID since you will not 'know' what it is when inserting into the carslibrary table. That said you could alter your DDL for the facerecord table to be:
CREATE TABLE `facerecord` (
`carslibrary_ID` int(10) unsigned NOT NULL,
`colorslibrary_ID` int(10) unsigned NOT NULL DEFAULT '0',
KEY `carslibrary_ID` (`carslibrary_ID`),
KEY `colorslibrary_ID` (`colorslibrary_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I've also changed the datatype of the colorslibrary_ID column to match that of the colorslibrary.ColorID column in case you ever feel like setting up a foreign key between facerecord.colorslibrary_ID and colorslibrary.ColorID ;). For the sake of completeness you should insert a row into the colorslibrary table with a ColorID = 0. Hence:
insert into `colorslibrary` (ColorName) values ('unknown color');
update `colorslibrary` set ColorID = 0 where ColorName = 'unknown color';
Then you can go ahead and define your trigger to insert into the facerecord table:
delimiter $$
CREATE TRIGGER carslibrary_trigger
AFTER insert ON carslibrary
FOR EACH ROW
BEGIN
insert into facerecord (carslibrary_ID) values (new.CarID);
END$$
delimiter;
All new rows inserted into the facerecord table will then be inserted with a colorslibrary_ID that relates to the 'unknown color' colorslibrary.ColorName.You can then manually update the facerecord.colorslibrary_ID as and when you know it.
Good luck!
PS If you need to remove any existing AFTER insert triggers from the carslibrary table you can do so by firstly finding the existing triggers:
select trigger_name
from information_schema.triggers
where event_object_table = 'carslibrary'
and action_timing = 'AFTER'
and event_manipulation= 'INSERT';
Then take the name of the trigger returned by the above statement (lets say the string 'carslibrary_trigger' is returned) and run:
drop trigger carslibrary_trigger;
Then re-run the CREATE TRIGGER script.
Once a trigger is set up it will automatically perform the action you have specified when the trigger action you have specified occurs. In this case we are telling the database "after an insert happens into the carslibrary table automatically insert a row into the facerecord table using the CarID of the new carslibrary row to populate the facerecord.carslibrary_ID column". As with most things the best way is to try it! Once you have created the trigger manually insert a new row into the 'carslibrarytable. Now look at the data in thefacerecord` table - you should see a new row that has been inserted by the trigger firing.
It sounds like you would benefit from learning about triggers. I recommend the docs on the MySQL site because this answer is way longer than I first intended it to be!
You will need to use triggers. See http://dev.mysql.com/doc/refman/5.0/en/triggers.html