【问题标题】:Unrecognised statement type (near IF)无法识别的语句类型(IF 附近)
【发布时间】:2017-12-12 17:05:17
【问题描述】:

我正在尝试编写一个 SQL 查询,当用户提供匹配的电子邮件和登录名时,它将更新我的数据库中的“密码”记录。我编写了下面的查询来尝试实现这一目标:

SET @password = 'password123';
SET @email = 'email';
SET @newPassword = 'pass54321';


IF `customer.Password` = @password WHERE `customer.Email` == @email
BEGIN
set `customer`.`Password` = @newPassword
END

我收到一条错误消息,提示“无法识别的语句类型(IF 附近)”。如果有人知道如何解决这个问题,任何帮助将不胜感激!我对使用 SQL 很陌生,所以这可能是完全错误的!!!

【问题讨论】:

  • 在 MySQL 中,IF 只允许在编程块——存储过程、函数和触发器中使用。

标签: mysql sql phpmyadmin


【解决方案1】:

我不是 mysql 用户,但在查看文档 (https://dev.mysql.com/doc/) 时,有几条路线可供选择。我正在向您展示 upsert 方式(这很酷,我以前从未见过)。

首先,您应该使用主键来帮助提高查找性能并帮助限定选择标准。

  # sample table with primary key
  CREATE TABLE customer (customer_id int not null primary key, name VARCHAR(20), email VARCHAR(20), password VARCHAR(20));

  # seed with data
  INSERT INTO customer VALUES(1,'John','john@email.com','password1');
  INSERT INTO customer VALUES(2,'Jane','jane@email.com','passwordx');

  # set test params
  SET @password = 'password1';
  SET @email = 'john@email.com';
  SET @newPassword = 'pass54321';

  /*
     depending on how the rest of the query is structured or if this
      doesn't fit the requirements...you have the option to use IF EXISTS

    This is using the 'ON DUPLICATE KEY UPDATE' to check if the record exists then performs an update if it does or an insert if it doesn't (aka upsert)

  */
  INSERT INTO customer VALUES (1, 'John', 'john@email.com', 'password1')
  ON DUPLICATE KEY UPDATE password = @newPassword;


  # test for password update
  SELECT * FROM customer WHERE customer_id = 1

如果您的表没有主键,请运行!使用If EXISTS 语句可能更有意义。

标记您组织中的某个人,以验证您所做的事情是否符合编码标准。使用 MySql 文档站点 - 它似乎维护得很好。

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 2020-08-30
    • 2019-01-16
    • 2021-11-24
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    相关资源
    最近更新 更多