MySql - ON DUPLICATE KEY INSERT

8
我知道存在INSERT IGNOREINSERT ... ON DUPLICATE KEY UPDATE。然而,在有重复键时,我希望将INSERT到临时表中以保留唯一键的记录,以便输出给用户。
是否有办法实现ON DUPLICATE INSERT?如果有帮助,我正在尝试进行批量插入。

可能是MySQL ON DUPLICATE KEY insert into an audit or log table的重复问题。 - Didier Spezia
2个回答

8

使用 ON DUPLICATE KEY UPDATE 语句时,不能将数据插入到另一个表中 - 也不存在其他可用的替代函数。

以下是两种自定义/替代方法:

  1. 使用存储过程,详细信息请参见此问题的已接受答案:MySQL ON DUPLICATE KEY insert into an audit or log table

  2. 创建一个触发器,将您表中的每个INSERT记录到另一个表中,并查询“日志”表中的任何重复项。

类似下面的内容应该可以工作:

CREATE TABLE insert_logs (
    id int not null
);

delimiter |
CREATE TRIGGER insert_logs_trigger BEFORE INSERT ON your_table
    FOR EACH ROW BEGIN
        INSERT INTO insert_logs SET id = NEW.id;
    END;
|

为了获取表格中重复数据的列表,您可以使用以下方法:
SELECT id FROM insert_logs HAVING COUNT(id) > 1 GROUP BY id;

0

也许这会有所帮助:

$time = time();
$countme = 1;
while ($countme > 0) {
    $stmt = $mysqli->prepare("INSERT INTO loads (dte,filecode,id,acct,nmbr) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE dte = dte");
    $stmt->bind_param("sssss", $time, $filecode, $id, $acct, $number);
    $stmt->execute();
    $countme++;
    if ($stmt->affected_rows === 1) {
        $countme = 0; // all is good
    } else {
        $time = $time + 1;
    }
    if ($countme === 4) {
        exit;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接