Kuroko Kuroko - 5 days ago 4
MySQL Question

MySQL Error, specifically an If Exist statement

I tried using from mySQL the If Exists statement but i got an error from mysql saying there's a #1064 syntax error, but i really couldn't find it. There are my codes:

If EXISTS (select * from points where username= 'john')
update points set points = "4" where username='john'
ELSE
insert into points (username, points) values ('john', 5);

Answer

One way to achieve your logic would be to use ON DUPLICATE KEY UPDATE while doing your INSERT:

INSERT INTO points (username, points)
VALUES ('john', 5)
ON DUPLICATE KEY UPDATE points=4

This query will insert ('john', 5') into your table, but if the primary key username john already exists, then it will points to 4.

Comments