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 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以获得正确的语法 '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
挣扎了这么久。请帮助。谢谢!
答案 0 :(得分:4)
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应该在SELECT
之前处理INSERT
,因此只应插入一行。
或者,您可以按两个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');
答案 1 :(得分:1)
这不是一个查询,这将是一个带有控制流逻辑的sql脚本,在存储的程序(过程,函数,触发器)之外的mysql中是不允许的。即使您将上述代码封装到存储过程中也不行,因为存在/不存在只能在子查询中使用。
我会做以下事情:
name='Rutvij' AND lang='python'
到变量中的行数。