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. But I am getting this error in the 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
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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.