如果不存在不工作

IF NOT EXIST NOT WORKING

IF NOT EXISTS(SELECT * FROM `user` WHERE `name`='Rutvij' AND `lang`='python')
    BEGIN
        INSERT INTO `user` VALUES ('Rutvij', 'python', 25)
    END
ELSE
    BEGIN
        UPDATE user SET `name`='Kanzaria' WHERE `name`='Rutvij'
    END

我正在 phpmyadmin sql 区域中尝试上述查询。我正在使用 xampp。抛出错误指出

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 EXISTS(SELECT * FROM user) SELECT name FROM use' at line 1

我也试过下面的代码

IF NOT EXISTS(SELECT * FROM user WHERE name='Rutvij' AND lang='python')
    BEGIN
        INSERT INTO user VALUES ('Rutvij', 'python', 25)
    END
ELSE
    BEGIN
        INSERT INTO user VALUES ('Kanzaria', 'python', 25)
    END

奋斗了这么久。请帮忙。谢谢!!

这不是查询,这将是一个具有控制流逻辑的 sql 脚本,这在 mysql 外部存储程序(过程、函数、触发器)中是不允许的。上面的代码即使封装成存储过程也行不通,因为exist/not exists只能在子查询中使用。

我会做以下事情:

  1. 创建 stored procedure
  2. 声明一个整型变量
  3. 使用 select into name='Rutvij' AND lang='python' 处的行数提取到您的变量中。
  4. 使用if语句根据记录数进行插入

MySQL 不允许 if 逻辑,除非您在编程块(存储过程、触发器或函数)中。

幸运的是,你可以用 WHERE 逻辑做同样的事情:

INSERT INTO user 
    SELECT 'Rutvij', 'python', 25
    FROM DUAL
    WHERE NOT EXISTS (SELECT 1 FROM user WHERE name = 'Rutvij' AND lang = 'python')
    UNION ALL
    SELECT 'Kanzaria', 'python', 25
    FROM DUAL
    WHERE EXISTS (SELECT 1 FROM user WHERE name = 'Rutvij' AND lang = 'python');

MySQL 应该在 INSERT 之前处理 SELECT,因此只应插入一行。

或者,您可以按两个 INSERT 执行此操作,但顺序相反:

INSERT INTO user 
    SELECT 'Kanzaria', 'python', 25
    FROM DUAL
    WHERE EXISTS (SELECT 1 FROM user WHERE name = 'Rutvij' AND lang = 'python');

INSERT INTO user 
    SELECT 'Rutvij', 'python', 25
    FROM DUAL
    WHERE NOT EXISTS (SELECT 1 FROM user WHERE name = 'Rutvij' AND lang = 'python');