It sounds so simple... I spent a few hours just getting the first part working which was a mysql trigger to a different database. Now I want to get smart and JOIN a couple tables.
I have two master tables PROJ and COMP. Both share id. When PROJ gets inserted I want to insert some of the NEW.PROJ info and some of the COMP info into a single row in the db.table axis.axis_data
Would someone please help me do a SELECT...INSERT with a TRIGGER. I might be in over my head on this one
My WORKING Trigger.
DELIMITER $$
DROP TRIGGER IF EXISTS `rate_data_trigger` $$
CREATE TRIGGER rate_data_trigger
BEFORE INSERT on PROJ FOR EACH ROW
BEGIN
INSERT INTO axis.axis_data
(projinfo_table_id, rate_user, name,
property_owner, property_address, property_city,
property_state, property_zip, property_phone,
rating_date, rating_type, rating_reason, rating_number
)
VALUES
(NEW.id, user(), NEW.BLGNAME,
NEW.POWNER, NEW.STREET, NEW.CITY,
NEW.STATE, NEW.ZIP, NEW.PHONE,
NEW.RATDATE, NEW.RATTYPE, NEW.RATREAS, NEW.RATNGNO
);
END$$
DELIMITER ;
Simply use the following syntax in your select statement:
INSERT INTO axis.axis_data
(projinfo_table_id, rate_user, name,
property_owner, property_address, property_city,
property_state, property_zip, property_phone,
rating_date, rating_type, rating_reason, rating_number,
field1, field2
)
SELECT NEW.id, user(), NEW.BLGNAME,
NEW.POWNER, NEW.STREET, NEW.CITY,
NEW.STATE, NEW.ZIP, NEW.PHONE,
NEW.RATDATE, NEW.RATTYPE, NEW.RATREAS, NEW.RATNGNO,
c.field1, c.field2
FROM COMP c WHERE c.id = NEW.id
If COMP doesn't always have a corresponding record in PROJ, you can do use SELECT ... FROM DUAL LEFT JOIN COMP c ON c.id = NEW.id
Related
This is my first trigger in MySql and I am having a few problems. I tried both of these pieces of code but both would not compile. I got it to work without the where clause.
CREATE TRIGGER ins_meal_details
AFTER INSERT ON meal_details
FOR EACH ROW
INSERT INTO sql_changes
SET
sc_table='book_room',
sc_reason='DINNER1',
sc_key='bh_no=NEW.bh_no,date=NEW.md_date',
sc_value='1',
sc_done =0
WHERE not exists (select 1 from booking where bh_no = NEW.bh_no and bo_date = NEW.md_date and bo_meals < 1)
CREATE TRIGGER ins_meal_details AFTER INSERT meal_details FOR EACH ROW
BEGIN
IF NOT EXISTS (select 1 from booking where bh_no = NEW.bh_no and bo_date = NEW.md_date and bo_meals < 1) THEN
INSERT INTO sql_changes (sc_table, sc_reason, sc_key, sc_value, sc_done )
VALUES ('book_room','DINNER1', 'bh_no=NEW.bh_no,date=NEW.md_date','1', 0);
END IF
END
CREATE TRIGGER ins_meal_details
AFTER INSERT
ON meal_details
FOR EACH ROW
INSERT INTO sql_changes (sc_table,
sc_reason,
sc_key,
sc_value,
sc_done)
SELECT 'book_room',
'DINNER1',
CONCAT('bh_no=',NEW.bh_no,',date=',NEW.md_date),
1,
0
WHERE NOT EXISTS (SELECT 1
FROM booking
WHERE bh_no = NEW.bh_no
AND bo_date = NEW.md_date
AND bo_meals < 1);
MySql did not like the select/where exists in my code when there is no table specified. This was due to using version 5.6 of MySql server.
This will not work: select 'works' where exists (select 1 from my-table)
The fix would be thanks to #akina to add from DUAL. The best solution.
I got round it by using a count(*) instead :-
DROP TRIGGER IF EXISTS ins_meal_details;
DELIMITER //
CREATE TRIGGER ins_meal_details
AFTER INSERT ON meal_details FOR EACH ROW
BEGIN
IF (select count(*) from booking where bh_no = NEW.bh_no and bo_date = NEW.md_date and bo_meals < 1) > 0 THEN
INSERT INTO sql_changes (sc_table,
sc_reason,
sc_key,
sc_value,
sc_done)
VALUES ('book_room','DINNER1', CONCAT('bh_no=',NEW.bh_no,',date=',NEW.md_date),'New Value', 0);
END IF;
END//
DELIMITER ;
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.
I have two tables DailyVisits and TotalSum My goal is to add DailyVisits to TotalSum with a stored procedure/query that I'll run at the end of the day.
DailyVisits
UserId,PageId,Visits
1,1,32
2,123,34
4,12,213
5,1,1
TotalSum
UserId,PageId,TotalVisits
1,1,300
1,41,2
3,12,213
5,1,653
and so on.
I tried two approaches but I can't get my head around a solution.
Below my queries to achieve this, if you have another suggestion/query simple enough to understand, I appreciate your help.
Approach1:
delimiter $$
CREATE PROCEDURE UPSERT_DAILYSUM()
BEGIN
IF EXISTS (SELECT Id, PageId FROM DailyVisits) THEN
UPDATE TotalSum TotalVisits = TotalVisits + (SELECT Visits FROM DailyVisits);
ELSE INSERT INTO TotalSum (UserId,PageId,TotalVisits)
VALUES (SELECT Id,PageId,Visits);
END IF
END $$
delimiter ;
Approach2:
INSERT INTO TotalSum (UserId,PageId,TotalVisits) VALUES(SELECT * FROM DailyVisits)
ON DUPLICATE KEY UPDATE (PageId,TotalVisits)
VALUES(SELECT PageId,Visits FROM DailyVisits)
This is what I'm struggling with: How will I get distinct values when key does not exist? Can I use RIGHT JOIN (or LEFT JOIN) and check for NULL values, and then add right (or left) table?
same as you need like this:
The problem is i dont know what you want to do in update and insert portion:
delimiter $$
CREATE PROCEDURE UPSERT_DAILYSUM()
BEGIN
Declare idvar int(50) DEFAULT 0;
Declare pageidvar int(50) DEFAULT 0;
SELECT Id, PageId INTO idvar,pageidvar FROM DailyVisits;
if(LENGTH(idvar)>0 THEN
UPDATE TotalSum TotalVisits = TotalVisits + (SELECT Visits FROM DailyVisits);
ELSE
INSERT INTO TotalSum (UserId,PageId,TotalVisits) VALUES (SELECT Id,PageId,Visits);
END $$
delimiter ;
I wrote a trigger INSERT AFTER: with I inside SELECT AND JOIN.
DROP TRIGGER IF EXISTS `InsertArticle`;
DELIMITER //
CREATE TRIGGER `InsertArticle` AFTER INSERT ON `article`
FOR EACH ROW
insert into log (LogTime, LogIdNote, LogName, LogType, LogIdUser, logTypeCategory, LogTypeUser, LogUrl)
select NEW.ArticleTime, NEW.idArticle, NEW.ArticleName, 1, NEW.ArticleToUserID, NEW.ArticleCategory, u.UsersTypeAccount, ct.URLCategorysubscribetotype
from users u where u.idUsers = NEW.ArticleToUserID LEFT JOIN categorysubscribetotype ct ON ct.CategoryTypeCategorysubscribetotype = 1;
END
//
DELIMITER ;
When I tried to create trigger, I get error 1422.
May be I have a wrong trigger sintax?
Try This:
DROP TRIGGER IF EXISTS `InsertArticle`;
DELIMITER //
CREATE TRIGGER `InsertArticle` AFTER INSERT ON `article`
FOR EACH ROW
insert into log (LogTime, LogIdNote, LogName, LogType, LogIdUser, logTypeCategory, LogTypeUser, LogUrl)
select NEW.ArticleTime, NEW.idArticle, NEW.ArticleName, 1 as LogType, NEW.ArticleToUserID, NEW.ArticleCategory, u.UsersTypeAccount, ct.URLCategorysubscribetotype
from users u LEFT JOIN categorysubscribetotype ct ON ct.CategoryTypeCategorysubscribetotype = 1 where u.idUsers = NEW.ArticleToUserID;
END
//
DELIMITER ;
I am trying to create a live update in a history table. Whenever record is inserted/updated in o_training approval table , a corresponding record should be INSERTED in o_training_appr_history table. For this i created below triggers.
appr_after_insert
**DELIMITER $$
create trigger olattest.appr_after_insert after insert on o_training_approval
for each row
BEGIN
INSERT INTO o_training_appr_history
select
NEW.request_id,
NEW.user_id,
m.band,
m.grade,
NEW.approver_id,
NEW.approver_role,
NEW.project_id,
NEW.course_id,
NEW.comments,
NEW.submitted_date,
NEW.status_id,
m.vertical,
m.sub_vertical,
m.city,
m.location_type as location
from o_training_approval t join o_master_employees m
on(t.user_id = m.emp_id)
where m.emp_id=NEW.user_id;
END;
$$**
appr_after_update
**DELIMITER $$
create trigger olattest.appr_after_update after update on o_training_approval
for each row
BEGIN
INSERT INTO o_training_appr_history
select
NEW.request_id,
NEW.user_id,
m.band,
m.grade,
NEW.approver_id,
NEW.approver_role,
NEW.project_id,
NEW.course_id,
NEW.comments,
NEW.submitted_date,
NEW.status_id,
m.vertical,
m.sub_vertical,
m.city,
m.location_type as location
from o_training_approval t join o_master_employees m
on(t.user_id = m.emp_id)
where m.emp_id=NEW.user_id;
END;
$$**
Both the triggers got created without any error. However, on insert/update on the base table , no record is getting inserted in the history table.
I am clueless as for the reason and solution. Could anyone please help in this regard?