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 ;
Related
I am trying to create a trigger in mysql that updates Table B with values from Table C, after a new record is inserted into Table A. I've tried a few variations of the code below, but can't get it to work. Can anyone point me in the right direction?
delimiter //
CREATE TRIGGER updateC AFTER Insert ON Table A
FOR EACH ROW in TableB
BEGIN
IF TableB.Group = 1 THEN
Insert into TableC(inserthere) values (TableB.AddThis);
END IF;
END;//
delimiter ;
Table A includes the fields ProjectID | TaskGroup.
Table B includes the fields ID | DefaultTask | TaskGroup.
Table C includes the fields ID | ProjectID | DefaultTask.
When a new ProjectID & TaskGroup are added to table A, I would like to find all DefaultTasks in TableB that have the same TaskGroup, and then insert those DefaultTasks & the ProjectID as new records in Table C
After You e explanation in the comment.
This shows you how to do it, you Must test The INSERT Query, it assumes that id is an autoincrement.
Every NEW.columname is the value of the inserted row.
With INSERT INTO ... SELCT You can male a bulk insert from all Values from Taböleb that fit the bill
DELIMITER //
CREATE TRIGGER updateC AFTER Insert ON TableA
FOR EACH ROW
BEGIN
INSERT INTO TableC (ProjectID,DefaultTask) SELECT NEW.ProjectID,DefaultTask
FROM TABLEB
WHERE TaskGroup = NEW.TaskGroup;
END;//
DELIMITER ;
FYI: Write sql Comands in UPPER case, it smales the reading much more simple
Can anyone point me in the right direction?
The record inserted into A must define the record(s) in B which must be updated, and the records in C which values must be taken for this update.
For example, it may be
CREATE TRIGGER updateC
AFTER INSERT
ON Table A
FOR EACH ROW
UPDATE B, C
SET B.field1 = C.field2
WHERE B.field3 = NEW.field4
AND C.field5 = NEW.field6;
I have two tables:
Table 1 : parts
id (primary key)
code
title
quantity
Table 2 : bill_items
id (primary key)
bill_id
parts_id: refers to primary key of table parts
qty
I would like to update parts table - qty every time I create a row in table bill_items. The qty in parts table is to be decremented by qty of bill_items. There may be N number of updates to table bill_items in one go. Would like to use a single INSERT....ON DUPLICATE or UPDATE statement.
Thank you for your time.
I think for this case better using trigger :
DELIMITER $$
CREATE
TRIGGER `bill_items_after_insert` AFTER INSERT
ON `bill_items`
FOR EACH ROW BEGIN
UPDATE parts set quantity = quantity - NEW.qty WHERE id = NEW.parts_id;
END$$
DELIMITER ;
I suggest you also make trigger for UPDATE and DELETE also for data consistency.
UPDATED
Based on your comment, it is possible to use normal insert and update using transaction for consistency data :
START TRANSACTION;
INSERT INTO bill_items (bill_id, parts_id, qty) VALUES (your_bill_id,your_parts_id,your_qty);
UPDATE parts SET quantity = quantity - your_qty WHERE id = your_parts_id;
COMMIT;
I want to write a trigger in MySQL which copy table1’s column1 to table2’s column1
But table2’s column1 must to be unique, table1’s column1 is duplicable.
Any one suggest me how to conditionally sync up between this 2 tables using triggers.
You could improve your question by stating what kind of trigger you want (insert,update,delete) and what you want to happen if a duplicate is found. Assuming you want an insert trigger and table2.id has unique key you could use insert ignore to ignore the error and throw away the the attempted insert from table1 , you could use insert..on duplicate key to update table2. If table2.id does not have a unique key you could code to find if the key would be duplicated and then apply the insert option you prefer. I have assumed that you don't simply want to throw an error if a duplicate is encountered. Here's some sample code and data for you.
DROP TABLE IF EXISTS TABLE1,TABLE2;
CREATE TABLE TABLE1(ID INT, VALUE INT);
CREATE TABLE TABLE2(ID INT PRIMARY KEY, VALUE INT);
DROP TRIGGER IF EXISTS T;
DELIMITER $$
CREATE TRIGGER T AFTER INSERT ON TABLE1
FOR EACH ROW
BEGIN
INSERT IGNORE INTO TABLE2 VALUES (NEW.ID,NEW.VALUE);
END $$
INSERT INTO TABLE1 VALUES(1,1);
SELECT * FROM TABLE2;
INSERT INTO TABLE1 VALUES(1,2);
SELECT * FROM TABLE1;
SELECT * FROM TABLE2;
DROP TRIGGER IF EXISTS T;
DELIMITER $$
CREATE TRIGGER T AFTER INSERT ON TABLE1
FOR EACH ROW
BEGIN
INSERT INTO TABLE2 VALUES (NEW.ID,NEW.VALUE)
ON DUPLICATE KEY UPDATE VALUE = NEW.VALUE;
END $$
DELIMITER ;
SELECT * FROM TABLE2;
INSERT INTO TABLE1 VALUES(1,3);
SELECT * FROM TABLE1;
SELECT * FROM TABLE2;
DROP TRIGGER IF EXISTS T;
DELIMITER $$
CREATE TRIGGER T AFTER INSERT ON TABLE1
FOR EACH ROW
BEGIN
DECLARE FOUND INT DEFAULT 0;
SELECT 1 INTO FOUND FROM DUAL WHERE EXISTS(SELECT ID FROM TABLE2 WHERE ID = NEW.ID);
IF FOUND = 0 THEN
INSERT INTO TABLE2 VALUES (NEW.ID,NEW.VALUE);
ELSE
INSERT INTO TABLE2 VALUES (NEW.ID,NEW.VALUE)
ON DUPLICATE KEY UPDATE VALUE = NEW.VALUE;
END IF;
END $$
DELIMITER ;
SELECT * FROM TABLE2;
INSERT INTO TABLE1 VALUES(1,4),(2,1);
SELECT * FROM TABLE1;
SELECT * FROM TABLE2;
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
basically I have these both tables.
What I want to do is upon INSERTION of content in the second table (table 2) I want its value at NULL to be filled with the id from table 1 in which the pairs formed by part1/part2 from table 1 and part1/part2 from table 2 remain the same (please notice they can exchange between them). What is the best way to do this?
What you can do is create a trigger on Insert like below
CREATE TRIGGER grabIdFromTable1
BEFORE INSERT ON table2
FOR EACH ROW
BEGIN
SET NEW.id = (SELECT id FROM table1 WHERE part1 = NEW.part1
AND part2 = NEW.part2
);
END//
see this sqlFiddle