MYSQL INSERT IF SUMs > CONSTANT
if-statement, insert, mysql, sum, where-clause
Solution
Try this:
INSERT INTO table2 (user, column1, column2)
select '0', 'd', '100'
from dual
where (SELECT SUM(num1 + num2) FROM table1 WHERE user = '0') +
(SELECT SUM(num3) FROM table2 WHERE column1 = 'd' AND user = '0') > 100;
This is a case of the general solution for a "insert if condition" problem:
insert into ... select ... where condition
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.
Problem
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 `IF`s, `WHERE`'s etc. Found you can't put `SUM`s in `IF`s, `WHERE`'s etc. I'm at a total loss. Here's an example of my earlier bad code before unsuccessfully trying to use `SUM`s in `WHERE`s, 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; ```