Mysql trigger to insert on two connected tables - mysql

I have 3 mysql tables:
user_followers has columns id,user_id
notification has columns id,user_id
notification_object has columns notification_id , type
On insert on user_followers i want to insert
user_id=New.user_id in notification
and then using the id of notification just inserted
notification_object.type = "2" and notification_object.notification_id = just inserted id in notifcication table
now the problem is how can i find the id of notifcation table:
DELIMITER //
CREATE TRIGGER follow_notification AFTER INSERT ON user_friends
FOR EACH ROW
Begin
insert into notification(user_id) values(New.user_id);
insert into notification_object(notification_id,type) values(????,"2");
End
//

if notifications.id is auto-incremented, mysql includes a function last_insert_id() that will return (with caveats) the lastly inserted id.
DELIMITER //
CREATE TRIGGER follow_notification AFTER INSERT ON user_friends
FOR EACH ROW
Begin
declare v_notification_id INT;
insert into notification(user_id) values(New.user_id);
/* set a variable to the last id inserted to the db */
set v_notification_id=(select last_insert_id());
/* use the variable in the next insert */
insert into notification_object(notification_id,type) values(v_notification_id,"2");
End//

Related

mysql before insert trigger does not work when trying to insert a new row

I created a Before Insert MySQL trigger to check if few values already exists on the table, but the trigger is not working.
This is my trigger:
DELIMITER $$
CREATE TRIGGER TEST1
BEFORE INSERT
ON roles FOR EACH ROW
BEGIN
DECLARE atExists INT DEFAULT 0;
SELECT count(id) FROM roles WHERE personal_id = NEW.personal_id AND role = NEW.role AND favorite = New.favorite INTO atExists;
IF (atExists = 0) THEN INSERT INTO roles (personal_id, role, favorite) VALUES (NEW.personal_id, NEW.role, NEW.favorite);
END IF;
END $$;
DELIMITER;
I have a row that has for example values:
999999999, "admin", "abcde"
and when I try to do
INSERT INTO roles (personal_id, role, favorite) values (999999999, "admin", "abcde");
After running the trigger, it does adds the new row even though it should just skip it.
I tried with IF NOT EXISTS (...) etc, did not work.
I also checked the SELECT to see if it does find the existing rows and it does.

Why I have this error in my trigger? MySQL

I am creating a MySQL database, I want to create a trigger to change the amount of inventory available after a sale, but I get an error
This is the code of the trigger
DROP TRIGGER IF EXISTS tr_inventario;
CREATE TRIGGER tr_inventario AFTER INSERT ON factura FOR EACH ROW
UPDATE producto INNER JOIN factura ON producto.IdProducto=factura.IdProducto
SET producto.Invenatario=producto.Invenatario-factura.Cantidad
WHERE producto.IdProducto=factura.IdProducto;
This is the INSERT that i want to do
INSERT INTO factura(FechaVenta, NombreCliente, IdProducto, IdEmpleado, Cantidad) VALUES (now(), 'MarĂ­a Guadalupe',3, 2, 2);
And this is the error that I get
Error Code: 1048. Column 'Invenatario' cannot be null
relational table
You don't need a JOIN:
DELIMITER $$
CREATE TRIGGER tr_inventario AFTER INSERT ON factura FOR EACH ROW
BEGIN
UPDATE producto p
SET p.Invenatario = p.Invenatario - new.Cantidad
WHERE p.IdProducto = new.IdProducto;
END;

MySQL - Insert Into 2 Tables on 1 Procedure

I need to create a procedure for inserting records into 2 tables, but on the second table, I want to insert the last ID that was inserted on the first table. Could anyone help me with this?
This is my query
DELIMITER //
DROP PROCEDURE IF EXISTS ROOM_FEATURE_INSERT;
CREATE PROCEDURE ROOM_FEATURE_INSERT (propID INT, featID INT, featNme VARCHAR(50))
BEGIN
-- BEGIN CHECK
IF NOT EXISTS
(
SELECT rFeatureName FROM COMPANY_T3s71.PROPERTY_RFEATURE PRFE
INNER JOIN COMPANY_T3s71.ROOM_FEATURE RFEA ON PRFE.rFeatureID=RFEA.rFeatureID
WHERE BINARY rFeatureName = featNme AND propertyID = propID
)
AND
(
SELECT rFeatureName FROM COMPANY_T3s71.ROOM_VIEW
WHERE BINARY rFeatureName = featNme
)
THEN
-- IF NOT EXISTS INSERT INTO 1st TABLE
INSERT INTO COMPANY_T3s71.ROOM_FEATURE (rFeatureName) VALUES (featNme);
END IF;
-- END CHECK
-- BEGIN CHECK 2nd TABLE
IF NOT EXISTS
(
SELECT propertyID, rFeatureID FROM COMPANY_T3s71.PROPERTY_RFEATURE
WHERE rFeatureID = featID AND propertyID = propID
)
THEN
-- IF NOT EXISTS INSERT INTO 2nd TABLE
INSERT INTO COMPANY_T3s71.PROPERTY_RFEATURE (propertyID, rFeatureID) VALUES (propID, featID);
END IF;
-- END CHECK 2nd TABLE
END
DELIMITER ;
How do we pass the featID param, when we just inserted it on the first INSERT query?
Thank you before hand.
Use SET featID = LAST_INSERT_ID(); after the first query and then use the variable
INSERT INTO COMPANY_T3s71.ROOM_FEATURE (rFeatureName) VALUES (featNme);
SET featID = LAST_INSERT_ID();
However, if the data is not insert at anytime then you have to make query in the if block to set the value for featID.

insert in to two table using one query inner join

I have two tables. One is user_info and the other is user_login. I want to insert data into both these tables in one query using an inner join. The data comes from user registration.
My login table:
user_id(pk) user_name user_password
1 jinesh secret
2 mahesh secret
My info table:
user_id(fk) name address phno
1 jinesh n banglore 9845***
2 mahesh m chennai 7345**
You can't make one query to insert values in two tables
However if you want to have the two querys in only one statement then
this can be done if you seperate the statements with ;
$query = "insert into table_1 (data1, data2) values ('value1', 'value2');insert into table_2 (data1,data2) values ('value1', 'value2')";
The best way is to use Stored Procedure.
CREATE PROCEDURE `Proc_User` (IN username VARCHAR(225), IN password VARCHAR(255),
IN uname VARCHAR(255),IN addr VARCHAR(255),IN phno VARCHAR(20))
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION, SQLWARNING
BEGIN
-- ERROR or WARNING
ROLLBACK;
END;
START TRANSACTION;
DECLARE userid INT;
INSERT INTO login (user_name,user_password) VALUES(username,password);
SET userid = (SELECT LAST_INSERT_ID());
INSERT INTO info(user_id,name,address,phno)
VALUES(userid,uname,addr,password);
COMMIT;
END
And to call the Stored Procedure in PHP
$proc = mysqli_prepare('CALL Proc_User(?, ?, ?,?,?);');
mysqli_stmt_bind_param('sssss', $username, $password, $name,$address,$phoneno);
mysqli_stmt_execute($proc);

mysql trigger error with 2 conditions

I want to add an after insert trigger which will do the following.
The first IF condition works normally, but when it comes to the second everything stops.
Any ideas?
USE `Syslog`;
DELIMITER $$
CREATE TRIGGER `SystemEventsR_AINS` AFTER INSERT ON SystemEventsR FOR EACH ROW
IF
(exists
(select syslogtag from SystemEventsRcounter where syslogtag=
new.syslogtag)
AND
(select simpledate from SystemEventsRcounter
where syslogtag=new.syslogtag)=new.simpledate)
THEN
UPDATE SystemEventsRcounter
SET records=records+1
WHERE SystemEventsRcounter.syslogtag=new.syslogtag;
ELSE INSERT SystemEventsRcounter (simpledate, syslogtag, records) values (new.simpledate,new.syslogtag,1);
END IF
UPDATED:
What you need is INSERT INTO ... ON DUPLICATE KEY.
CREATE TRIGGER `SystemEventsR_AINS`
AFTER INSERT ON SystemEventsR
FOR EACH ROW
INSERT INTO SystemEventsRcounter (simpledate, syslogtag, records)
VALUES (NEW.simpledate, NEW.syslogtag, 1)
ON DUPLICATE KEY UPDATE records = records + 1;
In order for it to work you need to create a unique composite index on (simpledate, syslogtag)
CREATE UNIQUE INDEX idx_u_simpledate_syslogtag
ON SystemEventsRcounter (simpledate, syslogtag);
Here is SQLFiddle demo.
If you wanted it your way then it might look like
DELIMITER $$
CREATE TRIGGER `SystemEventsR_AINS`
AFTER INSERT ON SystemEventsR
FOR EACH ROW
BEGIN
IF (
SELECT COUNT(*) simpledate
FROM SystemEventsRcounter
WHERE syslogtag = NEW.syslogtag
AND simpledate = NEW.simpledate
) > 0 THEN
UPDATE SystemEventsRcounter
SET records = records + 1
WHERE SystemEventsRcounter.syslogtag = NEW.syslogtag;
ELSE
INSERT INTO SystemEventsRcounter (simpledate, syslogtag, records)
VALUES (NEW.simpledate, NEW.syslogtag, 1);
END IF;
END$$
DELIMITER ;
Here is SQLFiddle demo.