我正在尝试创建一个 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)
);
最佳答案
这是可以做到的,因为您可以 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)
);
关于mysql - 插入带条件的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22866606/