IF ELSE STATEMENT for the Differnce of two columns in MYSQL - mysql

I have 3 tables : badge_master, match_result_updation and team_badges.
The badge_master is the master table where I manually insert the data acc to the excel. On match_result_updation I have some columns, if sum(goal_column1) - sum(goal_column2) = 10, then the value column1 will get the badge and it will be inserted in team_badges table. I am handling it through trigger but unable to proceed after certain time.
The trigger which I tried :
CREATE TRIGGER `afterinsert_teamgoals` AFTER INSERT ON `match_result_updation` FOR EACH ROW
BEGIN
DECLARE goalCount1 INT(10);
DECLARE goalCount2 INT(10);
DECLARE badgeId BIGINT(20);
DECLARE teamId bigint(20) default 0 ;
SELECT team1_goal INTO goalCount1 FROM match_result_updation WHERE team1_id = NEW.team1_id ;
SELECT team2_goal INTO goalCount2 FROM match_result_updation WHERE team2_id = NEW.team2_id ;
IF (goalCount1 - goalCount2 >= 10)
Then
Insert into team_badges(team_id,badge_id,match_id,timestamp)
SELECT teamId , badgeId , match_id FROM match_result_updation limit 1;
END IF;
Please Assist.

Related

How to SELECT multiple values in MYSQL trigger?

how can I SELECT multiple values INTO variables in MYSQL trigger?
I have tried SELECT values into variables in this way but it didn't work. I was inspired by this thread how to use trigger to set value based on query result.
When I examined value in variables, it is NULL. When I put this SELECT into mysql workbench it will select right values. I check column types and they are same type as variables in trigger.
With debug I discovered that there is problem with SELECTing values.
Thank you in advance.
Here is my trigger:
CREATE TRIGGER fin_den_zam_insert
AFTER INSERT
ON table1 FOR EACH ROW
BEGIN
DECLARE koef1 DECIMAL(6,3);
DECLARE koef2 DECIMAL(6,3);
DECLARE koef3 DECIMAL(6,3);
DECLARE sum DECIMAL(6,3);
SELECT DISTINCT
koef_salary, koef_sunday, koef_holiday
INTO
koef1 , koef2, koef3
FROM
employee E
WHERE
E.personal_number = NEW.personal_number_id;
SET sum := NEW.salary * (koef1 + koef2 + koef3);
INSERT INTO export_table
(
id_export,
personal_number,
final_sum
)
VALUES
(
NULL,
NEW.personal_number_id,
sum
);
END;
//
DELIMITER ;
You must be careful with reserved words like sum, that can cause very much trouble-
most people write before every own variable _ like _sum, so that also a stranger can identofy such variables.
That is as you can see not absoltely necessary, but helps also when you tale a look in 5 years
create table employee
(personal_number int,koef_salary DECIMAL(6,3), koef_sunday DECIMAL(6,3), koef_holiday DECIMAL(6,3));
create table export_table(
id_export int auto_increment primary key,
personal_number int,
final_sum DECIMAL(6,3)
);
CREATE table table1
(id_export int auto_increment primary key
, personal_number_id int
, salary DECIMAL(6,3));
insert into employee values(1,1.1,1.3,1.4);
CREATE TRIGGER fin_den_zam_insert
AFTER INSERT
ON table1 FOR EACH ROW
BEGIN
DECLARE koef1 DECIMAL(6,3);
DECLARE koef2 DECIMAL(6,3);
DECLARE koef3 DECIMAL(6,3);
DECLARE final_sum DECIMAL(6,3);
SELECT DISTINCT
koef_salary, koef_sunday, koef_holiday
INTO
koef1 , koef2, koef3
FROM
employee E
WHERE
E.personal_number = NEW.personal_number_id;
SET final_sum := NEW.salary * (koef1 + koef2 + koef3);
INSERT INTO export_table
(
id_export,
personal_number,
final_sum
)
VALUES
(
NULL,
NEW.personal_number_id,
final_sum
);
END
INSERT INTO table1 VALUES (NULL,1,100)
SELECT * FROM export_table
id_export | personal_number | final_sum
--------: | --------------: | --------:
1 | 1 | 380.000
db<>fiddle here

i want to insert same record for status=0 for the below code in mysql. but my logic is not working.can any one suggest me

I want to insert same record for status=0. But my logic is not working in MySQL.
Please add more text over here...
This question is about a stored procedure. And the user didn't provide any info what so ever.
CREATE DEFINER=`root`#`localhost` PROCEDURE `sp_insert2`(
IN P_page_Id int(11) ,
IN P_LanguageCode char,
IN P_page_status int(11),
IN p_created_by int(11),
IN p_created_date datetime,
OUT P_return int)
BEGIN
DECLARE v_isRecordExisting int;
DECLARE v_flags int;
SELECT
COUNT(*)
INTO
v_isRecordExisting
FROM
tbl_cms_pages_languages2
WHERE
page_status in(0,1)
AND
page_id = p_page_Id
AND
languagecode = P_LanguageCode;
IF
v_isRecordExisting = 0
THEN
INSERT INTO tbl_cms_pages_languages2 (
page_Id,
LanguageCode,
page_status,
created_by,
created_date
)
VALUES(
P_page_Id,
P_LanguageCode,
P_page_status,
P_created_by,
p_created_date
);
SET
p_return = 0;
ELSE
SET
p_return = 2;
END IF;
END

declaring variable inside mysql stored procedure

we are trying to declare a variable inside mysql stored procedure that has transaction implemented in it. but it seems to be giving a syntax error :
following is the syntax of the stored procedure:
CREATE PROCEDURE `sp_MarkAppointmentRefferal`(
p_AppId bigint,
p_NewLocation bigint,
p_userId bigint,
p_ReferralReason varchar(500),
p_NewLocationName varchar(100)
)
begin
declare v_OldLocation int default 0;
set v_OldLocation = (select LocationId FROM appointments where iAppID = p_AppId limit 1 );
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
select -1;
END;
START TRANSACTION;
update table
set is_referred = 1,
referred_timestamp = now(),
referral_reason = p_ReferralReason
where iAppID = p_AppId
limit 1;
-- create a new appointment for the new referred location..
insert into appointments
(vAppName, vAppType, dAppDate, vCell, iPatID, iAppStatus, iuserid, iActive,
dInsertDate, iHSID, daily_ticket_no, LocationId, visit_id, encounter_id, ReferredFrom,ReferredOPDName, opd_name )
select vAppName, vAppType, now(), vCell, iPatID, iAppStatus, p_userId,
1, now(), iHSID, fn_GenerateNextAppointmentTicket(now(),p_NewLocation) , p_NewLocation, visit_id, encounter_id+1,
(select LocationId FROM appointments where iAppID = p_AppId limit 1),
(select OPD_Name FROM appointments where iAppID = p_AppId limit 1), p_NewLocationName
FROM appointments
where iAppID = p_AppId limit 1;
select LAST_INSERT_ID();
COMMIT;
end;
the syntax checker is saying that declare command is not valid here.
have also tried to place this inside the transaction clause and similar error shows up ..
any help is appreciated..
All declare statements should be at the top of the stored procedure body. Moving DECLARE EXIT HANDLER before the SET statement should fix the problem.

Slope-One recommender implementation using mysql stored procedure

I am trying to implement Slop-One recommender using mysql stored procedure, the query runs okay and doesn't give any error. But it is not inserting/updating the 'dev' table.
The structure of tables are:
rating (user_id, article_id, rating_value, date)
dev (article1_id, article2_id, count, sum)
The 'dev' table has joint primary key (article1_id, article2_id). The sql for my procedure is as follows:
DELIMITER $$
CREATE PROCEDURE update_matrix(IN user INT(11), IN article INT(11), IN rating TINYINT(1))
BEGIN
DECLARE article_id2 INT(11);
DECLARE rating_diff TINYINT(1);
DECLARE done TINYINT(1) DEFAULT 0;
DECLARE mycursor CURSOR FOR
SELECT DISTINCT article_id, (rating - rating_value)
FROM rating
WHERE user_id = user AND article_id != article;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN mycursor;
FETCH mycursor INTO article_id2, rating_diff;
WHILE(!done) DO
INSERT INTO dev (`article1_id`, `article2_id`, `count`, `sum`)
VALUES (article, article_id2, 1, rating_diff)
ON DUPLICATE KEY UPDATE count = count + 1, sum = sum + rating_diff;
INSERT INTO dev (`article1_id`, `article2_id`, `count`, `sum`)
VALUES (article_id2, article, 1, -rating_diff)
ON DUPLICATE KEY UPDATE count = count + 1, sum = sum - rating_diff;
FETCH mycursor INTO article_id2, rating_diff;
END WHILE;
CLOSE mycursor;
END$$
DELIMITER ;

Stored Procedure taking ages to execute?

DELIMITER $$
CREATE PROCEDURE Load_Fact_List()
BEGIN
DECLARE Project_Number_Temp INT;
DECLARE Panel_Id_Temp INT;
DECLARE Employee_Id_Temp INT;
DECLARE Zip_Temp VARCHAR(255);
DECLARE Created_Date_Temp DATE;
DECLARE Country_Temp VARCHAR(255);
DECLARE no_more_rows BOOLEAN;
DECLARE loop_cntr INT DEFAULT 0;
DECLARE num_rows INT DEFAULT 0;
DECLARE load_cur CURSOR FOR
SELECT Project_Id, Panel_Id, Employee_Id, Zip, Created_Date
FROM Fact_List;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET no_more_rows = TRUE;
OPEN load_cur;
select FOUND_ROWS() into num_rows;
the_loop: LOOP
FETCH load_cur
INTO Project_Number_Temp, Panel_Id_Temp, Employee_Id_Temp, Zip_Temp, Created_Date_Temp;
IF no_more_rows THEN
CLOSE load_cur;
LEAVE the_loop;
END IF;
SET Country_Temp= (select Country from Zip where Zip= Zip_Temp);
INSERT INTO Test_Fact
(
Project_Key,
Campaign_Key,
Respondents_Key,
Event_Key,
Employee_Key,
Geography_Key,
Date_Key
)
SELECT (SELECT Project_Key from Project_Dim where Project_Id= Project_Number_Temp AND Quota_Country= Country_Temp),0,(SELECT MAX(Respondents_Key) from Respondents_Dim WHERE Panel_Id= Panel_Id_Temp),1,(select MAX(Employee_Key) from Employee_Dim WHERE Employee_Id= Employee_Id_Temp),(Select Geography_Key from Geography_Dim where Zip= Zip_Temp), (Select Date_Key from Date_Dim where Full_Date= Created_Date_Temp);
SET loop_cntr = loop_cntr + 1;
END LOOP the_loop;
select num_rows, loop_cntr;
END $$
The above code is properly working but it is damn slow. For every 1 hour it is loading 1000 records. I got lacks of records to load into fact table. can anyone suggest me any optimization?
Requirement is to load fact table by looping through other table and gathering required key values from dimension tables.
The usual procedure is actually like this.
You have your dimensions built and you just gathered the data you want to insert into your fact table in a temporary table. Then you insert this data in another temporary table like this:
INSERT INTO tmp_fact_table
(
fact_key,
dim1_key,
dim2_key,
...
fact1,
fact2
...
)
SELECT
ISNULL (f.fact_key, 0),
ISNULL (d1.sid, 0) as whatever,
ISNULL (d2.sid, 0) as whatever2,
...
ISNULL (tt.fact1, 0),
ISNULL (tt.fact2, 0)
FROM
yourTempTable tt
LEFT JOIN Dim1 d1 ON tt.identifying_column = d1.identifying_column
...
LEFT JOIN fact_table f ON
f.dim1_key = d1.sid
AND f.dim2_key = d2.sid
where
fact_key is the identifying column in your fact table
dim1_key is the foreign key in your fact table to the dimensions
fact1 and so on are the facts you want in your fact table, clear
the ISNULL() function returns 0 when no entry is found. 0 is the id of your dummy row in each dimension for unknown data
Then you will have a table where you have the IDs of your dimensions linked to the data you want to import into your fact table with 0 as fact key when the entry in the fact table does not already exist and the ID of the fact table entry otherwise.
Then you update the fact table where tmp_fact_table.fact_key != 0
Then you insert into the fact table where tmp_fact_table.fact_key = 0
That's it.
I'm doing this with millions of rows and it takes about half an hour. 300,000 rows is peanuts.