插入..重复键更新 - 重复插入


Insert...on duplicate key update- repeatedly inserting

在我的文档表中,我有: id (auto int index), user_id (P.key and links to other table), Doc_Name, abstract

当我使用下面的代码时,它只是插入另一行,所以我有两个user_id在应该更新时是相同的。显然,id 只是在数量上继续存在,因为它是自动 int,我不确定这是否与它不起作用的原因有关。

 $the_query = sprintf("INSERT INTO `document` (`user_id`,`Doc_Name`,`abstract`)
 VALUES ('%d','%s','%s')",'$user_id', '$Doc_Name', '$abstract')
 ON DUPLICATE KEY UPDATE
 user_id=user_id+'$user_id',
 Doc_Name=Doc_Name+'$Doc_Name',
 abstract=abstract+'$abstract' "
 );

货物崇拜编程?使用没有任何%占位符的 sprintf() 只是....错。同样,为什么要在更新的字段上添加?

MySQL使用concat()进行连接。 +纯粹是一种数学运算。做'a' + 'a'不会给你aa,你会得到0

如果user_id是表中的唯一字段,则查询应如下所示:

$query = sprintf("
INSERT INTO
    `document`(`user_id`, `Doc_Name`, `abstract`)
VALUES
    ('%s', '%s', '%s')
ON DUPLICATE KEY UPDATE
    `Doc_Name` = VALUES(`Doc_Name`),
    `abstract` = VALUES(`abstract`)
", $user_id, $Doc_Name, $abstract);