简体   繁体   中英

Insert if record not exists else delete in mysql with a long query

I have a follow system that allow user to follow one another. I'm using php pdo so it doesn't support multiple line query instead I need a long query. Currently I'm using the code below

$query = $db->query("SELECT id FROM follow WHERE user1 = 'kim' AND user2 = 'tim' ");
if($query->rowCount() > 0 ){
    $db->query("DELETE * FROM follow WHERE user1 = 'kim' AND user2 = 'tim' ");
}else{
    $db->query("INSERT INTO follow (user1,user2) VALUES ('kim','tim') ");
}

So here what I want is a long query rather than multiple query statement. Additional with the long query I need get the data that indicate wether the record is insert or delete.(Maybe this question is duplicated but this is the part that wasn't duplicated) How can I acheive it?

Here is the "long query"

IF EXISTS (SELECT id FROM follow WHERE user1 = 'kim' AND user2 = 'tim' )
BEGIN
    DELETE * FROM follow WHERE user1 = 'kim' AND user2 = 'tim'
END
ELSE
BEGIN
    INSERT INTO follow (user1,user2) VALUES ('kim','tim')
END

If it gets too "long" put it in a stored procedure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM