无法识别的语句类型(在IF附近)

时间:2017-12-12 17:05:17

标签: mysql sql phpmyadmin

我正在尝试编写一个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很新,所以这可能是完全错误的!

1 个答案:

答案 0 :(得分:0)

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

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

  # 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 docs网站 - 看起来它维护得很好。