[英]if exists update else insert mysql
IF EXISTS (SELECT * FROM two_player WHERE title='math' and user2 is null)
UPDATE two_player SET score2='50' , user2='zahra' WHERE title='math' and user2 is null
ELSE
INSERT INTO two_player (user1,score1,title) values ('zahra', '50', 'math')
This query works right in sql server. 此查询在sql server中正常运行。 But I am getting this error in the mysql:
但是我在mysql中收到此错误:
*#1064 - You have an error in your SQL syntax;
*#1064-您的SQL语法有误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS (SELECT * FROM two_player WHERE title='math' and user2 is null) ' at line 1
在第1行上,检查与您的MySQL服务器版本相对应的手册,以获取在'IF EXISTS(SELECT * FROM two_player WHERE title ='math'并且user2为null)'附近使用的正确语法。
why?! 为什么?! what is the alternative for that?
那有什么选择呢?
You can use Store Procedures to solve this problem like below 您可以使用存储过程来解决此问题,如下所示
DELIMITER $$
DROP PROCEDURE IF EXISTS `select_or_insert`$$
CREATE PROCEDURE select_or_insert()
begin
IF EXISTS (SELECT * FROM test WHERE id="id") THEN
SELECT * FROM test WHERE id="id";
ELSE
INSERT INTO test (id,name) VALUES ("id",'name');
END if;
END$$
DELIMITER ;
and call it like this: 并这样称呼它:
call select_or_insert();
Use replace instead update or insert:- 使用替换代替更新或插入:-
REPLACE INTO two_player (user1,user2,score1,score2,title) values ('zahra', 'zahra','50','50', 'math')
In this case you must have a unique index. 在这种情况下,您必须具有唯一索引。
Else according to your programming language try this:- 另外,根据您的编程语言,请尝试以下操作:-
UPDATE two_player SET score2='50' , user2='zahra' WHERE title='math' and user2 is null
if updates_rows == 0:
INSERT INTO two_player (user1,score1,title) values ('zahra', '50', 'math')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.