mysql - INSERT '100' into table IF '100' 是最高值给出错误

标签 mysql sql if-statement

根据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/

相关文章:

sql - 使用大表的 WHERE EXISTS 查询可扩展性

java - 如何在 IF 语句中使用数组?

mysql:如果求和则嵌套

MySQL CHARACTER SET utf8mb4 VARCHAR 长度

mysql - 在存储过程中使用游标的语法错误

sql - 如何最好地在 MySQL 数据库中存储年、月和日?

sql - Access 和 ODBC/Oracle 都能理解的通用 SQL

java - 如何在 Processing 中允许可编程键输入?

php - 事件调度程序计算结果的 if 条件

mysql - 在其包含的学生点的表中查找学生的排名