2

假设我有一张桌子:

CREATE TABLE files (
    id_prod INT UNSIGNED NOT NULL DEFAULT PRIMARY KEY AUTO_INCREMENT,
    id_rel INT UNSIGNED,
    name VARCHAR(250),
    other VARCHAR(200),
    UNIQUE INDEX(id_rel , name)
);

我想使用一个唯一的query来插入/更新这个表上的数据:

INSERT INTO files (id_rel , name)
VALUES ('25', 'test')
ON DUPLICATE KEY UPDATE

现在,阅读我读到的 MySQL 手册:

ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id)

所以我认为我的查询应该是:

INSERT INTO files (id_rel , name)
VALUES ('25', 'test')
ON DUPLICATE KEY UPDATE id_prod = LAST_INSERT_ID(id), name = 'TESTED'

但如果我只使用,那有什么区别:

INSERT INTO files (id_rel , name)
VALUES ('25', 'test')
ON DUPLICATE KEY UPDATE name = 'TESTED'

?

我无法理解 LAST_INSERT_ID(id) 的含义。什么是 (id) 以及它应该做什么?

4

1 回答 1

3

This is only necessary if your application needs to call LAST_INSERT_ID() after performing the INSERT. Normally, LAST_INSERT_ID() will only return a value if you actually inserted a new row into the table, not of there was a duplicate key and it updated the row instead.

From the documentation:

If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID().

If you use the idiom you quoted, LAST_INSERT_ID() will return either the ID of the new row that was inserted or the row that was updated.

于 2013-05-23T02:35:00.327 回答