mysql - 无法识别的语句类型(靠近 IF)

标签 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,所以这可能是完全错误的!!!

最佳答案

我不是 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 文档站点 - 它看起来维护得很好。

关于mysql - 无法识别的语句类型(靠近 IF),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47777946/

相关文章:

php函数导致sql查询失败

php - 如何在一个字段中插入多个具有不同id的数据?

mysql - ./libraries/plugin_interface.lib.php 中的 phpmyadmin 警告错误#551

mysql - 检查来自不同表的 ID

mysql - 当两个表中不存在相似数据时,在一个查询中更新两个表

mysql - 将外键插入表中

sql - 按特定顺序排序,包括NULL、postgresql

sql - 在Access中运行预建查询时语法错误3075

mysql - SQL - 即使 LEFT JOIN 失败也返回行

mysql - 显示两种状态的金额总和