简体   繁体   English

如果记录不存在则插入,否则在MySQL中删除带有长查询的内容

[英]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. 我正在使用php pdo,因此它不支持多行查询,而是需要一个长查询。 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. 如果它变得太“长”,则将其放入存储过程中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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