gpt4 book ai didi

mysql - 如果不存在不工作

转载 作者:行者123 更新时间:2023-11-29 01:27:22 25 4
gpt4 key购买 nike

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

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

最佳答案

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

幸运的是,您可以使用 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');

关于mysql - 如果不存在不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35819895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com