开发者

MySQL If exsists insert into or else do something else

开发者 https://www.devze.com 2023-04-06 01:13 出处:网络
I\'m having some difficulty putting a conditional into MySQL. I\'ve been trying to create a query that will go through all of the column titled email and if it exists I want to do something like this:

I'm having some difficulty putting a conditional into MySQL. I've been trying to create a query that will go through all of the column titled email and if it exists I want to do something like this: If an email exists I want it to take the existing value of the column correct and add the php variable $correct to it. But if an email does not exist then I want it to add a new record with the values $email into the column email and $correct into column correct. Any help would be greatly appreciated.

Here's what I have and does not work:

IF  (SELECT * FROM facebookqs WHERE email = '$email' > 0)
UPDATE facebookqs SET correct = correct + '$correct' where email ='$em开发者_运维技巧ail' 
Else
Insert into facebookqs (email, correct) VALUES ('$email', '$correct')


Assuming email has a UNIQUE constraint, you should use INSERT ... ON DUPLICATE KEY UPDATE

INSERT INTO facebookqs (email, correct) VALUES ('$email', '$correct')
ON DUPLICATE KEY UPDATE correct = correct + '$correct'

See also my answer for this other Stack Overflow question: INSERT IGNORE vs INSERT … ON DUPLICATE KEY UPDATE


Your missing an EXISTS statement and the THEN and END IF in the IF

IF  (EXISTS(SELECT * FROM facebookqs WHERE email = '$email')) THEN
  UPDATE facebookqs SET correct = correct + '$correct' WHERE email ='$email';
ELSE
  INSERT INTO facebookqs (email, correct) VALUES ('$email', '$correct');
END IF;


Use the REPLACE method, explained here: http://blogs.coldbuffer.com/inserting-or-updating-records-using-mysql-replace From their example:

REPLACE INTO pet (id, type, name) VALUES(1, 'Dog', 'Pluto');

which given your example should be (haven't tested it yet)

REPLACE INTO facebookqs (email, correct) VALUES ('$email', '$correct');


Do you need to select the e-mail column only? Or do you have multiple columns that contain e-mail addresses? If you have multiple columns with email then you would need to say where col1Email = '$email' or col2Email='$email'... etc. To get a count of the rows try SELECT COUNT(*) from facebookqs where col1Email = '$email' or col2Email='$email'.

0

精彩评论

暂无评论...
验证码 换一张
取 消