重复键更新时插入始终更新所有值

时间:2013-12-02 11:26:29

标签: php mysql sql

我正在尝试更新行或插入新行(如果存在)。如果有更新我只想用当前时间戳更新“更新”列,否则“添加”和“更新”得到相同的值(时间戳)

//1385982893 is from PHP with time() cause it's needed elsewhere too

INSERT INTO table (id, code, added, updated) VALUES (236, 'abcdefghi', 1385982893, 1385982893)
ON DUPLICATE KEY UPDATE
id = values(id), code = values(code), added = values(added),updated = 1385982893

ID是主键。代码是UNIQUE

问题是“添加”总是会使用当前时间戳(如更新的)更新

2 个答案:

答案 0 :(得分:4)

您只需要删除added = values(added),它就不会更新:

INSERT INTO table (id, code, added, updated) VALUES (236, 'abcdefghi', 1385982893, 1385982893)
ON DUPLICATE KEY UPDATE
id = values(id), code = values(code),updated = 1385982893

答案 1 :(得分:2)

然后不要在Update

中添加
INSERT INTO table (id, code, added, updated) VALUES (236, 'abcdefghi', 1385982893, 1385982893)
ON DUPLICATE KEY UPDATE
id = values(id), code = values(code), updated = 1385982893