I’m trying to insert a record if a sum of 3 user columns from 2 tables exceeds a constant.
I’ve searched all over, found you can’t put user variables in IFs, WHERE‘s etc. Found you can’t put SUMs in IFs, WHERE‘s etc. I’m at a total loss. Here’s an example of my earlier bad code before unsuccessfully trying to use SUMs in WHEREs, if it helps:
SELECT SUM(num1) INTO @mun1 FROM table1 WHERE user = '0';
SELECT SUM(num2) INTO @mun2 FROM table1 WHERE user = '0';
SELECT SUM(num3) INTO @mun3 FROM table2 WHERE column1 = 'd' AND user = '0';
SET @mun4 = @mun1 - @mun2 - @mun3;
INSERT INTO table2 (user, column1, column2) VALUES ('0', 'd', '100') WHERE @mun4 >= 100;
Try this:
This is a case of the general solution for a “insert if condition” problem:
The select will only return rows if the condition is true, and importantly, will return no rows if false – meaning the insert only happens if the condition is true, otherwise nothing happens.