I create a script/workflow exportation/importation from 2 system.
I have Table1 {id, name, description}
I want to create a script (not a procedure). I could (I didnt succed) adding procedure into my workflow. (create and delete at the end)
id is auto increment
I cant change the table
I can be sure that between the time I start execution of my script and the end, there will not be an insertion of one of my items into the database.
The script insert {name,description} but I want to NOT insert if the element (name or name and description) is there.
BASE QUERY :
INSERT INTO TABLE1 (name,description) VALUES ('itemX','this is item X')
BASE Script :
Use database1;
BEGIN;
SELECT * FROM TABLE1 ;
SELECT * FROM TABLE3 ;
INSERT INTO TABLE1 (name,description) VALUES ('itemX','this is item X');
set #idTable1 = LAST_INSERT_ID();
INSERT INTO TABLE3 (idTable1,idTable2) VALUES (#idTable1,1);
INSERT INTO TABLE3 (idTable1,idTable2) VALUES (#idTable1,2);
SELECT * FROM TABLE1 ;
SELECT * FROM TABLE3 ;
ROLLBACK;
I want to protect the multiple insertion on TABLE1. But without changing the table.
Maybe I did it wrong
I tried IF but not working outside procedure.
I tried IGNORE (valid only if id is the same, but never the same, its
auto increment)
I tried WHEN
I tried ON DUPLICATE KEY
Because of #idTable1, I will need change the " set #idTable1 = LAST_INSERT_ID();" if I doesnt have if else. But if my item is the only one with the same "name", I can get this instead of last_insert_id.
I opted for creating procedure before my "BEGIN" and removed them at the end of the script.
Just create the table with name as primary key, then be sure that you take care of the key capitalization (uppercase or lowercase) to avoid duplicates.
CREATE TABLE TABLE1(
id INT AUTO_INCREMENT,
name CHAR(30),
description CHAR(100),
PRIMARY KEY (name)
)
create unique constraint on name field if possible.
Otherwise, create trigger before insert in order to ignore duplicate insertion.
Trigger for checking duplicate on two fields a and b:
delimiter //
drop trigger if exists aborting_trigger //
create trigger aborting_trigger before insert on t
for each row
begin
set #found := false;
select true into #found from t where a=new.a and b=new.b;
if #found then
signal sqlstate '45000' set message_text = 'duplicate insert';
end if;
end //
delimiter ;
The trigger here provides feature similar to unique constraint. After creation you should use INSERT IGNORE or INSERT ...ON DUPLICATE KEY UPDATE
Related
I'm trying to create trigger to insert new data to item table, but it has to be checked if the new data exists or not in item table. Here is my code:
DELIMITER //
CREATE TRIGGER addItem
AFTER INSERT ON tempitem FOR EACH ROW
BEGIN
IF NOT EXISTS (SELECT * FROM item WHERE item_name = NEW.item_name) THEN
BEGIN
INSERT INTO item (item_code, item_name, kategori, satuan)
SELECT item_code, item_name, kategori, satuan FROM tempitem WHERE tempitem.item_name = NEW.item_name ;
END IF;
END;
//
DELIMITER ;
The error says there are syntax error near "IF; END;" in line 8, but I can't find any mistake in the syntax.
When using SQL, we don't check if data exists to be sure we won't add duplicates. We attempt to insert it and we place unique constraints. If the record exists, database tells us "No-no-no, it's already there" and that's it.
Solution to your problem is not a trigger, it's placing a unique index on item_name. Since item_name is probably a textual column (char, varchar, text), usual technique is to create an additional column that will contain the hash of item_name and you apply unique index to that one.
All that's left is to utilize one of MySQL extensions to SQL, namely INSERT IGNORE syntax or INSERT INTO ... ON DUPLICATE KEY UPDATE and your problem is solved forever.
You have an extra "BEGIN" in line 7, after "THEN" that may be causing the problem.
Try
DELIMITER //
CREATE TRIGGER addItem
AFTER INSERT ON tempitem FOR EACH ROW
BEGIN
IF NOT EXISTS (SELECT * FROM item WHERE item_name = NEW.item_name) THEN
INSERT INTO item (item_code, item_name, kategori, satuan)
SELECT item_code, item_name, kategori, satuan FROM tempitem WHERE tempitem.item_name = NEW.item_name ;
END IF;
END;
//
DELIMITER ;
I have table1 & table2 (with foreign key) see tables :
I want query that can put same value automatically as
(INSERT INTO table2 (table2.foreignKey) VALUES (table1.id))
You can use a Trigger to do this.
It would look somewhat like this:
delimiter |
CREATE TRIGGER insertIntoTable2 AFTER INSERT ON table1
FOR EACH ROW
BEGIN
INSERT INTO table2 SET foreignKey = NEW.id;
END;
|
delimiter ;
I looked into MySQL duplicate key but cant figure it out.
I have a table like below:
id series chapter path(can be unique)
I want only insert data and not update. Lets say I have data like below:
seri:Naruto, klasor:567 ==> If both of these exist in table then do not insert.
seri:Naruto, klasor:568 ==> If Naruto exist but 568 does not exist then do insert.
How can I achieve this?
Easiest way would be to define unique index with two columns on that table:
ALTER TABLE yourtable ADD UNIQUE INDEX (seri,klasor);
You may also define two column primary key, which would work just as well.
Then use INSERT IGNORE to only add rows when they will not be duplicates:
INSERT IGNORE INTO yourtable (seri, klasor) VALUES ('Naruto',567);
INSERT IGNORE INTO yourtable (seri, klasor) VALUES ('Naruto',568);
Edit: As per comments, you can't use UNIQUE INDEX which complicates things.
SET #seri='Naruto';
SET #klasor=567;
INSERT INTO yourtable
SELECT seri,klasor FROM (SELECT #seri AS seri, #klasor AS klasor)
WHERE NOT EXISTS (SELECT seri, klasor FROM yourtable WHERE seri=#seri AND klasor=#klasor);
You may use the above query with two local variables or convert it to single statement by replacing the local variables with actual values.
Better way would be to use stored procedure:
CREATE PROCEDURE yourinsert (vseri VARCHAR(8), vklasor INT)
BEGIN
DECLARE i INT;
SELECT COUNT(*) INTO i FROM yourtable WHERE seri=vseri AND klasor=vklasor;
IF i=0 THEN
INSERT INTO yourtable (seri,klasor) VALUES (vseri, vklasor);
END IF;
END;
This would allow you to perform the INSERT using:
CALL yourinsert('Naruto',567);
INSERT INTO table_name (seri, klasor) VALUES ('Naruto',567)
WHERE NOT EXISTS( SELECT seri,klasor FROM table_name WEHERE seri='Naruto' AND klasor=567
)
Hope this helps..
I'm trying to insert new rows into a MySQL table, but only if one of the values that I'm inserting isn't in a row that's already in the table.
For example, if I'm doing:
insert into `mytable` (`id`, `name`) values (10, `Fred`)
I want to be able to check to see if any other row in the table already has name = 'Fred'. How can this be done?
Thanks!
EDIT
What I tried (can't post the exact statement, but here's a representation):
INSERT IGNORE INTO mytable (`domain`, `id`)
VALUES ('i.imgur.com', '12gfa')
WHERE '12gfa' not in (
select id from mytable
)
which throws the error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE '12gfa' not in ( select id from mytable)' at line 3
First of all, your id field should be an autoincrement, unless it's a foreign key (but I can't assume it from the code you inserted in your question).
In this way you can be sure to have a unique value for id for each row.
If it's not the case, you should create a primary key for the table that includes ALL the fields you don't want to duplicate and use the INSERT IGNORE command.
Here's a good read about what you're trying to achieve.
You could use something like this
INSERT INTO someTable (someField, someOtherField)
VALUES ("someData", "someOtherData")
ON DUPLICATE KEY UPDATE someOtherField=VALUES("betterData");
This will insert a new row, unless a row already exists with a duplicate key, it will update it.
DELIMITER |
CREATE PROCEDURE tbl_update (IN id INT, IN nm VARCHAR(15))
BEGIN
DECLARE exst INT;
SELECT count(name) INTO exst FROM mytable WHERE name = nm;
IF exst = 0 THEN
INSERT INTO mytable VALUES(id, name);
END IF;
END
|
DELIMITER ;
or just make an attribute name as UNIQUE
Based on my previous post found here im able to insert the values to the 2nd table when the status on first table changes, but it keeps adding indiscriminately, i need to check if the submit_id has already been inserted into the 2nd table and then update the fields not insert it gain, how would i do that check before the trigger is executed?
Because the new.status and old.status refer to the row being edited not the row on table it's being inserted into, how can i compare that and insert or update if it already exists,
Thanks
You can use INSERT INTO ... ON DUPLICATE KEY UPDATE syntax for that
If order for it to work properly you have to have a UNIQUE constraint on submitId column in your second table (let's call it students).
ALTER TABLE students ADD UNIQUE (submitId);
Now an improved version of a trigger
DELIMITER $$
CREATE TRIGGER tg_au_submissions
AFTER UPDATE ON submissions
FOR EACH ROW
BEGIN
IF NEW.status = 1 THEN
INSERT INTO students (submitId, studentName, submitDate, contacts, email)
VALUES (NEW.submitId, NEW.studentName, NEW.submitDate, NEW.contacts, NEW.email)
ON DUPLICATE KEY UPDATE
studentName = VALUES(studentName),
submitDate = VALUES(submitDate),
contacts = VALUES(contacts),
email = VALUES(email);
END IF;
END$$
DELIMITER ;
Here is SQLFiddle demo