【问题标题】:Update record if "title" already exists in table when inserting如果插入时表中已存在“标题”,则更新记录
【发布时间】:2015-12-05 20:38:13
【问题描述】:

我的 MySql 数据库中有 tag 表,如下所示。

Id    Title    RepeatCount
--------------------------
 1     Tag1        1
 2     Tag2        5
 3     Tag3        8

我想在PDO的表中插入记录,如果不存在具有相同Title的记录(Title是主键),如果存在,增加记录RepeatCount

像这个例子:

prepare(
    "IF (:Title IN (SELECT Title FROM tag)) 
     THEN INSERT INTO tag (Title) VALUES (:Title)
     ELSE UPDATE tag SET RepeatCount = RepeatCount + 1"
);
execute(array(
    ":Title" => "MyTag"
));

【问题讨论】:

标签: php mysql if-statement pdo


【解决方案1】:

在 MySQL SQL 中,if 等控制流语句仅在存储块中有效,例如存储过程、函数和触发器。执行此过程的更好方法是使用on duplicate key update

insert into tag(Title)
    values (:Title)
    on duplciate key update RepeatCount = RepeatCount + 1;

这更好,因为数据库可以处理竞争条件,因此您不必担心值被覆盖。注意:这里假设RepeatCount 被初始化为一个数字而不是NULL

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    相关资源
    最近更新 更多