根据MySQL documentation这将在 mysql.version > 5 上运行。但我得到:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF
代码:
IF SELECT MAX(`amount`) FROM transactions < 500
THEN
INSERT INTO transactions (amount) VALUES (500)
END IF
或
IF( (SELECT MAX(`amount`) FROM transactions < 500)
,INSERT INTO transactions (amount) VALUES (500)
, null
);
交易表:
id amount
1 100
2 150
3 400
都不起作用。
最佳答案
错误的原因是您不能在普通查询中使用 IF
语句,它只能在存储例程的上下文中使用(过程、函数、触发器、事件)。
您的第一段代码将在存储过程中成功运行只需稍加更改
DELIMITER $$
CREATE PROCEDURE insert500()
BEGIN
IF (SELECT MAX(`amount`) FROM transactions) < 500 -- see parenthesis around select
THEN
INSERT INTO transactions (amount) VALUES (500); -- semicolon an the end
END IF; -- semicolon an the end
END$$
DELIMITER ;
CALL insert500();
这里是SQLFiddle 演示
<小时/>现在这是一种在一条语句中完成您想要的操作的方法
INSERT INTO transactions (amount)
SELECT 500
FROM transactions
HAVING MAX(amount) < 500;
这里是SQLFiddle 演示
关于mysql - INSERT '100' into table IF '100' 是最高值给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19149650/