我正在尝试创建一个SQL查询,其中我需要检查来自2个表的列的总和,然后在满足条件时将新行插入另一个表中。我知道我可以使用带有显式锁定的存储过程,但想知道是否可以在单个SQL查询中执行此操作。我写了以下内容,但它在MySQL工作台中提供了语法错误
INSERT INTO table1 (`col1`, `col2`)
VALUES ('abc', 'xyz') WHERE
(
((select
COUNT(*) from table2 t2 where t2.id = 1)
+ (select sum(t3.counter) from table3 t3
WHERE t3.id = 1)) < (select t4.total_allowed
FROM table4 t4 where t4.id = 1)
);
答案 0 :(得分:3)
这可以做到,因为你可以insert the results of a select query。
INSERT INTO table1 (`col1`, `col2`)
SELECT 'abc', 'xyz'
FROM DUAL WHERE
(
((select
COUNT(*) from table2 t2 where t2.id = 1)
+ (select sum(t3.counter) from table3 t3
WHERE t3.id = 1)) < (select t4.total_allowed
FROM table4 t4 where t4.id = 1)
);
答案 1 :(得分:0)
MySQL INSERT
语法不支持WHERE
子句。