0

I have a table with 2 columns, they are 'user' and 'action' and are used to denote when a user has completed a certain action. An entry should only be made if a user has not made the given action before so I feel something like the following is what is required:

IF NOT EXISTS (select * from actiontable WHERE user=1 and action=5) THEN 
INSERT INTO actiontable VALUES(1,5);

Yet this seems to be incorrect syntax and I can't find how I should go about this. Is this possible? Or is there some way to use a primary key or unique key to achieve this?

4
  • This is back to front. Commented Feb 25, 2014 at 20:46
  • Is there any error when you are trying to execute this. Commented Feb 25, 2014 at 20:46
  • There is, I tried search for the code and the text separately but to no avail: #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 NOT EXISTS(SELECT * FROM actiontable WHERE user=1 AND action=5 at line 1 Commented Feb 25, 2014 at 20:50
  • 1
    @Sam . . . You can only use if in the context of a stored procedure, function, or trigger. Commented Feb 25, 2014 at 20:58

1 Answer 1

2

You could create a primary key on user,action and then try

INSERT INTO actiontable (`user`,`action`) VALUES (1,5);

It will fail if the entry already exists. If you do not want to raise an error, you could try

INSERT IGNORE INTO actiontable (`user`,`action`) VALUES (1,5);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.