如何结合ON DUPLICATE KEY UPDATE和WHERE


how to combine ON DUPLICATE KEY UPDATE with WHERE

我正在尝试使用INSERT ON DUPLICATE UPDATE,但我的问题是如何在此查询中使用WHERE ?

function add_link($id,$title,$url,$txt,$keyword,$category,$credit,$description,$active)
{
    $query = $this->dbh->prepare("INSERT INTO links ( id,  userId,  title,  url,  txt,  keyWord,  category,  credit,  description,  active,  status) VALUES 
                                                    (:id, :userId, :title, :url, :txt, :keyWord, :category, :credit, :description, :active, :status)
                                                    ON DUPLICATE KEY UPDATE 
    title=:title, url=:url, txt=:txt, keyWord=:keyWord, category=:category, credit=:credit, description=:description, active=:active, status=:status");
    $query->bindValue(":id",((int)$id==0)?NULL:((int)$id));
    $query->bindValue(":userId",$this->user['id']);
    $query->bindValue(":title",trim($title));
    $query->bindValue(":url",trim($url));
    $query->bindValue(":txt",trim($txt));
    $query->bindValue(":keyWord",trim($keyword));
    $query->bindValue(":category",(int)$category);
    $query->bindValue(":credit",(int)$credit);
    $query->bindValue(":description",trim($description));
    $query->bindValue(":active",(int)$active);
    $query->bindValue(":status",0);
    try{
        $query->execute();
        $this->error(0);
    }catch (PDOException $ex){
        $this->error(104); $this->errStr = $ex->getMessage(); return false;
    }
}

如果你检查我的查询,你会看到插入查询很好,更新也在工作,但是当更新查询执行时,我想检查userId与活跃用户,如果它是记录的所有者,然后刷新字段。

我在查询字符串的末尾尝试了这个:

WHERE userId=:userId

但它没有工作。

解决方案吗?

如果userId已经是唯一键,则不需要WHERE子句。ON DUPLICATE KEY UPDATE将只更新已经具有重复键的行,因此您不必自己处理此条件。