1

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.

Community
  • 1
  • 1
jibbajava
  • 17
  • 1
  • 2
  • 6

1 Answers1

1

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

Black Maggie
  • 496
  • 2
  • 15
  • So I do: `IF EXISTS(SELECT coaches.U_Name,coaches.P_word,coaches.M_ID FROM coaches WHERE coaches.U_Name="bob1" AND coaches.P_word="123") ON DUPLICATE KEY UPDATE U_Name = coaches.U_Name, P_word = coaches.P_word; 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;` Is this the correct format? – jibbajava Apr 10 '13 at 02:05
  • Apologies as I am still getting used to the editing system, ^^ looks a mess. – jibbajava Apr 10 '13 at 02:12
  • Why not have a try on the query browser for the results? – Black Maggie Apr 10 '13 at 05:28