Using Trigger to update database when insert is used - mysql

Im looking for a way to use triggers to update a row in a different table.
The table im trying to get the info from is AI (Auto increment) and also the primary key of that table.
My problem is that i cant find a simple way of doing it.
My code:
DROP TRIGGER IF EXISTS Konsistens;
DELIMITER $$
CREATE TRIGGER Konsistens AFTER INSERT ON PersonData
FOR EACH ROW
BEGIN
INSERT INTO Bruker(BrukerNavn, Passord, PersonId)
VALUES('Bruker1', 'pw1', LAST_INSERT_ID(PersonData.PersonID));
END
All i want is for PersonID to be given a value inside the Bruker table.
Since PersonID is a foreign key from Person to Bruker it doesnt seem to exist when i try to get the value from it. When i use this trigger it also creates a bug where i can no longer insert values into PersonData.
My desired result is that when you insert something into PersonData you get a new row into Bruker which have the same PersonID as the new entry in PersonData.

You just reference recenty inserted row by NEW
CREATE TRIGGER Konsistens
AFTER INSERT ON PersonData
FOR EACH ROW
INSERT INTO Bruker (BrukerNavn, Passord, PersonId)
VALUES(NEW.BrukerNavn, NEW.Passord, NEW.PersonId);

Related

FUNCTION does not exist error, trigger in MySQL

I am having this issue with my newly created database. I created my table and tried adding a prefix when adding data like it is shown in this question How to make MySQL table primary key auto increment with some prefix and came up with this trigger to use:
CREATE TRIGGER tg_contracts_insert BEFORE INSERT ON contracts
FOR EACH ROW
BEGIN
INSERT INTO contracts_seq VALUES (NULL);
SET NEW.cid = CONCAT('CN', LPAD(LAST_INSERT_CID(), 5, '0'));
END
cid being my primary key to be auto-inserted. I was apparently able to add the trigger However, when I tried adding my values on the main table, "contracts", with this:
INSERT INTO contracts (name, conres, conven, start, end, tipo) VALUES ('Roberto Grajales', 'Pedro', 'Pascual', '2022-12-12', '2022-08-08', 'Servicio');
name, conres, conven being VARCHAR type, start and end DATE and tipo being ENUM.
I get the following error message:
FUNCTION database.LAST_INSERT_CID does not exist
Anyone has any idea why and how to solve this?
Thanks!
There is no function LAST_INSERT_CID(). You probably meant LAST_INSERT_ID().

MySQL workbench 6.2 auto-increment

The problem is I have class_id,faculty_id,course_id,semester,day and time records in class table. The class_id in this table is auto-incremented, faculty_id and course_id are also auto_incremented in there own respective tables.
My question is, when I insert values of semester, day and time I want the rest of the three ids(class_id,faculty_id and course_id) to be auto-incremented. I tried it with the help of triggers but it is not incrementing all the records together but it is incrementing one after the other.
Here are the queries used:
CREATE DEFINER=`root`#`localhost` TRIGGER classINSERT AFTER INSERT ON `faculty` FOR EACH ROW
begin insert into class(faculty_id) values(new.faculty_id);
end
CREATE DEFINER=`root`#`localhost` TRIGGER classINSERT2 AFTER INSERT ON `course` FOR EACH ROW
begin insert into class(course_id) values(new.course_id);
end
I guess, you are mis interpreting the word "auto-increment" and its function with your current needs. From your two triggers i see you are trying to insert a new record into the tbl_class table when a new faculty/course is created.
CREATE DEFINER=`root`#`localhost` TRIGGER classINSERT AFTER INSERT ON `faculty` FOR EACH ROW
begin
insert into class(faculty_id) values(new.faculty_id);
end
above code tells me after insert on tbl_faculty insert a new record in to the tbl_class with newly created faculty_id. There is no sign of course_id. of course it will show as blank/null if you don't set it.
the same applies for the other trigger.
I'm not sure if this thats is your intention but AFAIK this does not make any sense. The tbl_class should be created with existing faculty_id and course_id probably a drop-down-box in your form.
in case if you want to create new course or new faculty while creating a new class record. that is completely different question from what you are asking now. That would require a new form taking the new faculty name and perform an insert on the table and refresh the drop-down-box.

update a table when new data is available in another table

I have two table:
Am using this query to populate my marks table with all 'id' in student table:
$module1= "insert into marks (stud_id,moduleID)
select sid, 1
from user_student
where sid not in (
select * from (
select distinct stud_id from marks where moduleID=1
) alias_name
)";
So i need to take all 'sid' from Table student and populate them into table marks my query above does all that. The problem am encountering is that every time i make a change to the data e.g column test1 , new record are inserted again.
If i populate the marks table manually, Can't i have a code that when new data is available in student table, the data is just updated in marks table...
I don't understand some points of your insert query, why insert sid in stud_id if there's a id in student table to relate them?
Maybe solve your problem the creation of a composed unique key to moduleID and stud_id and use a REPLACE in place of INSERT.
But the right way to do it is using a TRIGGER like:
DROP TRIGGER IF EXISTS `student_after_insert`;
CREATE TRIGGER `student_after_insert` AFTER INSERT ON `student`
FOR EACH ROW INSERT INTO marks (stud_id,moduleID)
SELECT NEW.`id`, `modules_table`.`id` FROM `modules_table`;
PS: I suppose you have a table of modules with name modules_table. Change it accordingly.
I haven't understand your question at the best, my tip is:
Make a unique constraint on marks table (up to you is the choice of best constraint rule).
Then use a trigger to make the right insert/update:
Something like that, (hope that syntax is right):
CREATE TRIGGER myTrigger
AFTER INSERT ON students
FOR EACH ROW
BEGIN
// check that insertion doesn't broke the constraint previously define, then
insert into marks (stud_id,moduleID) values (new.sid, 1);
END
Note: NEW is the row that you have as soon inserted/updated on students. Similar you have OLD metarow.

MySQL intercept insert with a trigger

Assume I have the following tables:
Globals:
id (Primary key, Int, Auto increment)
Table 1:
t1Id (Primary key, Int)
date (Key, Datetime)
I want the following behaviour, when I do INSERT INTO table1 (date) VALUES(NOW()) for example, I want that:
An TRIGGER gets called before the actual insert happens.
In the trigger it will insert a new entry in Globals table.
It will use that id as the t1Id for Table 1.
The original INSERT will now happen with the value for t1Id.
This should effectively create a sort of global unique identifier for all tables that are to be effected by this trigger.
My knowledge about TRIGGERs is how to react on them and do stuff after the original trigger condition has been fulfilled (in this case the insert), but I do not know how to properly implement this specific behaviour.
Something like:
CREATE TRIGGER ins_check AFTER INSERT ON table1
FOR EACH ROW
BEGIN
INSERT INTO Globals .... VALUES (NEW.t1Id)
END;
Row NEW contains the row as soon inserted. And so NEW.t1Id will contain the latest id added.
I would remove the primary key on Id column of the Globals table.
For details.

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