Populating two tables from another table using a trigger - mysql

I am having the following issue:
I currently have 3 tables:
Person(personID, firstName, lastName, ...)
Household(householdID, personID, sons, daughters, ...)
Info(infoID, firstName, lastName, sons, daughters, ...)
The Info table is where all of the data is currently, while Person and Household are empty and I would like to distribute the data by putting the persons data into the Person table, and their household data into the Household table. Household.personID is a foreign key to Person.personID.
I am attempting to do this by inserting one row at a time into household, and after each row I will insert the persons data into the Person table (which will assign that person a unique personID) and then go back and insert that new personID into the household table.
After looking around I have found that I should either be using a transaction or a by creating a trigger (or both?). I do not know much about either but this is what I have created from what I have read:
CREATE TRIGGER PersonTrigger AFTER INSERT ON Person
FOR EACH ROW BEGIN
INSERT INTO Household
(personID, sons, daughters, ...")
VALUES (LAST_UPDATE_ID(), (SELECT sons, daughters, ...
FROM Info)
END;
INSERT INTO Person (firstName, lastName, ...)"
SELECT firstName, lastName, ...
FROM Info
But when attempting to run this I am getting the SQLException error
SQLException: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'EACH ROW BEGIN INSERT INTO TestHousehold(personID, givenName, lastName' at line 1
Any insight as to why this may be happening would be greatly appreciated. Thanks in advance.

Try using this:
CREATE TRIGGER distributing_info_details AFTER INSERT ON Info FOR EACH ROW
BEGIN
INSERT INTO Household (personID, sons, daughters, ...)
VALUES (new.PersonID, new.sons, new.daughters, ...)
# use ^ this key word to access the newly inserted ID.
INSERT INTO Person (firstName, lastName, ...)
VALUES (new.firstName, new.lastName,...)
END;
Please note that the two insert statements must be both between the BEGIN and END tags. And also note that I attached this trigger after insert on the Info table, not on Person because you said that all data are currently put on Info table.
You didn't tell us whether sons and daughter also refers to another person (which in that case, sons and daughters are foreign keys), and will yield to a different set of codes for this trigger.
I hope this helps.

Related

MySQL DB Trigger Insert after cost linked to id

first Trigger I created.
I have two tables, student and cost.
If I insert a new student I want to automatically insert a cost row for this student in the table cost and insert the corresponding student id to the cost.
I donĀ“t know how I can link the student id to the cost...
CREATE TRIGGER `add_cost` AFTER INSERT ON `student` FOR EACH ROW INSERT INTO cost (amount) VALUES (2000)
Thanks everybody!!
In your insert statement please use just:
NEW.{primary_key}
from related table(in your case student). If your primary is id this should looks like:
NEW.id
NEW is created after row is inserted and contain all inserted values + PK after insert.
Finally your query should looks like below:
INSERT INTO cost (student_id, amount) VALUES (NEW.id, 2000)
You can find more info on http://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html

How do I grab info from one table while still adding values?

I'm working on a project and am trying to grab a key from another table while still grabbing from the values given. For example...
INSERT INTO Essay (student_ID, student_essay) VALUES (`Students.student_ID`, 'I WANNA BE THE VERY BEST');
I need to grab the student_ID from the Students table (otherwise the numbers will be off since student_ID is auto-increment), but I need to be able to insert the value of the essay.
You need to use the Max(id) function.
You can use Max(id) function also it will return max id and you are using auto increment so offcorse it will return last id and that last id you can insert in 2nd table, like:
INSERT INTO Essay (student_ID, student_essay)
VALUES ((SELECT MAX(s_id) from Students), 'I WANNA BE THE VERY BEST');
here is S_id means you need to provide that id which you want to use in Students table.
I'm not sure what you want, but probably you only need an INSERT from SELECT.
INSERT INTO Essay (Student_id, Student_essay)
SELECT student_id, ? student_essay
FROM Student
WHERE name = ?;
You can find this in the docs: Insert from select MySQL
Question Marks represent the values that you will send from the application.
This should solve your problem:
INSERT INTO Essay (Student_id, Student_essay)
SELECT student_id, 'I WANNA BE THE VERY BEST' student_essay
FROM Student
WHERE email = 'asdajo#hota.com';

mysql create multiple tables from one table

I have one table which I have imported into mysql.
Now I need to create multiple related tables.
So basically I have currently got the following
start transaction;
Insert into Address (AddressLine1, AddressLine2, Town, County, Postcode)
Select Distinct Address_line_1, Address_Line_2, Town, County, Postcode from Import;
set addressLastId = last_insert_id();
INSERT INTO Organisation (Name, AddressID)
SELECT DISTINCT Supplier_Name, addressLastId FROM Import;
commit;
The second part where I use the last_insert_id never increments probably because it gets the last insert.
So I need to workout how i can get the previous id for each row inserted into the address table?
Would i need to have an inner loop within the address insert ?
Cheers
I agree with Tim.
After you've populated Address, then you could just run
INSERT INTO Organisation (Name, AddressID)
SELECT DISTINCT Import.Supplier_Name, Address.id
FROM Import INNER JOIN Address ON (set all the address lines and city etc =, since Im guessing there wasnt an address ID in the original import)
You could use a join for the second insert - join Address and Import, and insert the required fields from each into Organisation.
Getting the last insert ID will only work if you process each record sequentially.

MySQL - Trigger that will automatic insert on other table

How can I create a trigger that will insert data into another table.
For example: I have a department table and a course table and the course table has a foreign key named department_id.
I insert CICCT into the course table but there is no CICCT in the department table.
My goal is to make the trigger add the value in the department table. How can I do this?
I tried this, is this correct?
CREATE TRIGGER department_insert BEFORE INSERT
ON course
FOR EACH row
begin
INSERT INTO department
(department_id,
description)
VALUES (new.id_dep,
NULL);
end;
Another question in the same subject, what do I need to do in order reduce the room capacity by one when a student enrolls?
Your trigger might look like this
CREATE TRIGGER department_insert
BEFORE INSERT ON course
FOR EACH ROW
INSERT IGNORE INTO department (department_id, description)
VALUES (NEW.id_dep, NULL);
Note:
to access column values of a row being inserted you have to use the NEW keyword
NEW.id_dep
^^^
use IGNORE clause in INSERT to ignore department_id values if they already exist in department table. It allows to greatly streamline your code.
Here is SQLFiddle demo
Make a separate post for your second question and specify table schemas

Trigger insert deleted row

Hello I have some difficulties with simple trigger in MSSQL 2008.
I want to insert deleted row to another table.
Here is my trigger code:
use databasex;
GO
CREATE TRIGGER DeleteEmployee
ON Employees
FOR DELETE
AS
BEGIN
INSERT INTO DeletedEmployees (Name, Surname, Function)
VALUES (deleted.Name, deleted.Surname, deleted.Function)
END
Employees table:
Name Surname Function ...
DeletedEmployees table:
Name Surname Function ...
I need somehow to specify that deleted columns are from deleted table, but how ?
I dont want to write subquery for every column.
How it being done ?
ps: is there any good tutorial on using triggers ? i believe i will need write more triggers in the future.
DELETED is a virtual table you select from (you may have deleted more than one row, so a single value is not enough)
Also, FUNCTION is a reserved word and needs to be escaped
CREATE TRIGGER DeleteEmployee
ON Employees
FOR DELETE
AS
BEGIN
INSERT INTO DeletedEmployees (Name, Surname, [Function])
SELECT Name, Surname, [Function] FROM deleted
END
An SQLfiddle to test with.