SQL - Insert or Update with a result from another table - mysql

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 ;

Related

IN clause not working in WHERE condition in MYSQL Trigger

I am creating a trigger that have a MYSQL query having IN clause look like below.
drop trigger onPublish;
delimiter $$
create trigger onPublish AFTER insert on publish_drawing_details
for each row
begin
Declare userIds VARCHAR(255);
set userIds = (select GROUP_CONCAT(refUser) from manpower where refProject=new.refProjectId and refRoleType in (select role from hr_user));
insert into notification_container(loginUserId,mailSubject,projectId,userIds,attachmentIds,ccMails,mailText,metaNotificationEventId)
values (new.submittedBy,new.mailSubject,new.refProjectId,userIds,new.attachmentIds,new.ccEmails,new.mailText,1);
end $$
It works fine if I write this like set userIds = (select GROUP_CONCAT(refUser) from manpower where refProject=new.refProjectId and refRoleType in (1,2,3,4,5));
I try it like set userIds = (select GROUP_CONCAT(refUser) from manpower where refProject=new.refProjectId and refRoleType in (select GROUP_CONCAT(role) from hr_user));
but don't work at all.
You don't need GROUP_CONCAT in inner query, try the following:
SET userIds = (
SELECT GROUP_CONCAT(refUser)
FROM manpower
WHERE refProject=new.refProjectId
AND refRoleType IN (
SELECT role
FROM hr_user
)
);

mysql procedure with if condition

I'm in my first databases class and I'm trying to write a conditional block for a mysql procedure.
This is the procedure:
delimiter //
CREATE PROCEDURE add_ascent(IN cid INT, IN pid INT)
BEGIN
DECLARE count_ascents INT;
SET count_ascents = 0;
SELECT COUNT(`cid`) INTO count_ascents FROM ascents WHERE `cid`=cid AND `pid`=pid;
IF count_ascents < 1 THEN
INSERT INTO ascents (`cid`, `pid`) VALUES (cid, pid);
UPDATE climbers SET climbers.ascents = climbers.ascents + 1 WHERE climbers.id=cid;
UPDATE problems SET problems.ascents = problems.ascents + 1 WHERE problems.id=pid;
END IF;
END;
//
delimiter ;
The goal of the procedure is to only perform the insert and updates if the (cid, pid) pair is not in the the ascents database. After testing, the program doesn't seem to go into the if block at all.
FYI, you might want to consider using an UPSERT, instead of "select/if/insert". For example, mySQL offers INSERT ON DUPLICATE KEY UPDATE.
Here, I suggest:
giving your parameters a DIFFERENT name than the column name, for example iCid and iPid, then
Typing SELECT COUNT(cid) INTO count_ascents FROM ascents WHERE cid=iCid AND pid=iPid and checking the result.

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.

WHILE LOOP not working as intended in mysql PROCEDURE

I have 100 rows in table tbl_master_sales and an empty table tbl_customer_sales.When I use WHILE loop to insert data from tbl_master_salesto tbl_customer_sales,it only inserts 50 rows.However,it should have insert 100 rows taking two iteration of while loop.What may be my mistake in following PROCEDURE:
CREATE PROCEDURE ROWPERROW()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
SELECT COUNT(*) FROM tbl_master_sales INTO n;
SET i=0;
WHILE i<n DO
INSERT INTO tbl_customer_sales (id,card_number,customer_name,customer_phone,bill_no,item_code,division,section,department,item_name,store,promo_name,billdiscount_name,billqty,promo_amount,bill_discount_amount,loyaltyamount,net_amount)
SELECT id, card_number, customer_name, customer_mobile, billno, itemcode, division, section, department, itemname, store, promoname, billdiscountname, billqty, promoamount, billdiscountamount, loyaltyamount, netamount
FROM tbl_master_sales
WHERE NOT EXISTS(SELECT 1
FROM tbl_customer_sales
WHERE id=tbl_master_sales.id)
LIMIT i,50;
SET i = i + 50;
END WHILE;
End;;
I don't see anything wrong with your procedure code logic but the reason for inserting only 50 rows could be the NOT EXISTS part shown below, which is restricting from inserting duplicate rows (or) filtering out the rest records.
WHERE NOT EXISTS(
SELECT 1
FROM tbl_customer_sales
WHERE id=tbl_master_sales.id)

Insert into change value if duplicate entry

I have this sql query:
INSERT INTO my_table
SELECT id, name, type
FROM other_table
I have this row: 1,bob,male
And I try insert: 1,bob,male
So, I have a duplicate entry error and I want change my insert value with an increment by one so after I would have two rows:
bob,male <=NOT UPDATED
bob,male
I don't want update the existing row, if I have a duplicate entry error. The insert increments the id value. So, I think ON DUPLICATE KEY isn't the solution.
UPDATE:
If I use a trigger like this:
DELIMITER |
CREATE TRIGGER incremente_primary BEFORE INSERT ON my_table FOR EACH ROW
BEGIN
IF( EXISTS( SELECT * FROM my_table )) THEN
SET NEW.id = NEW.id + 1;
END IF;
END |
DELIMITER ;
It doesn't work because a trigger can read only one line.
As per your requirement, you need to set auto_increment property for your id and then just insert other columns except id, so that it can be auto_increment like below-
INSERT INTO my_table (name,type)
SELECT name, type
FROM other_table;
If you just want to ignore if there is duplicate then you can use-
INSERT IGNORE INTO my_table
SELECT id,name, type
FROM other_table;
make sure that the primary key isn't the name or the type. Because you can input duplicate rows as long as you do not duplicate primary keys
I find a solution, i use a cursor:
DROP PROCEDURE proc_incremente;
DELIMITER |
CREATE PROCEDURE proc_incremente()
BEGIN
DECLARE var_name, var_type VARCHAR(100);
DECLARE var_id INT;
DECLARE end TINYINT(1) DEFAULT 0;
DECLARE cursor_incremente CURSOR
FOR SELECT * FROM other_table;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET end = 1;
OPEN cursor_incremente;
loop_cursor: LOOP
FETCH cursor_incremente INTO var_id, var_name, var_type;
IF end = 1 THEN
LEAVE loop_cursor;
END IF;
WHILE ( EXISTS( SELECT * my_table WHERE id = var_id) IS TRUE) DO
SET var_id = var_id + 1;
END WHILE;
INSERT INTO my_table(id,name,type) VALUES(var_id,var_name,var_type);
END LOOP;
CLOSE cursor_incremente;
END |
DELIMITER ;
CALL proc_incremente();