Question

Quick question. I am currently using INSERT... SELECT statement to check a user has a basic member account before they become a coach. This code works fine:

INSERT into coaches (U_Name, P_word, M_ID)
SELECT members.U_Name,members.P_word,members.M_ID FROM members
WHERE members.U_Name="bob1" AND members.P_word="123"
ON DUPLICATE KEY UPDATE U_Name = members.U_Name, P_word = members.P_word;


As you can see I am currently just updating their account with the same data if they already exist. What I want to do now is if the user is a member and has already become a coach, to display a message informing them they are already registered as a coach.
So my question is, do I wrap this in an IF... ELSE statement or do I use an IF EXISTS statement such as this insert if not exists else just select in mysql
Was thinking along the lines of:

IF EXISTS(SELECT coaches.U_Name,coaches.P_word,coaches.M_ID FROM coaches 
WHERE coaches.U_Name="bob1" AND coaches.P_word="123")
ELSE
BEGIN
INSERT into coaches (U_Name, P_word, M_ID)
SELECT members.U_Name,members.P_word,members.M_ID FROM members
WHERE members.U_Name="bob1" AND  members.P_word="123"
END;

Have also looked at this example here: MySql IF exists select ELSE insert but not sure how I would implement it. Any instructions on where to go from here would be appreciated.

Was it helpful?

Solution

INSERT ... ON DUPLICATE KEY UPDATE Syntax can help you on resolving the issue. It is available starting on mySQL 5.0

Reference: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top