如果存在则更新否则插入 mysql

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')

此查询在 sql 服务器中有效。但是我在 mysql:

中收到此错误

*#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 two_player WHERE title='math' and user2 is null) ' at line 1

为什么?! 有什么替代方案?

使用替换代替更新或插入:-

REPLACE INTO two_player  (user1,user2,score1,score2,title) values ('zahra', 'zahra','50','50', 'math')

在这种情况下,您必须具有唯一索引。

否则根据你的编程语言试试这个:-

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')

您可以使用存储过程来解决这个问题,如下所示

    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 ;

并这样称呼它:

call select_or_insert();