我有一种情况,我需要根据两个字段(两个外键)更新或插入表,我无法设置UNIQUE约束(因此INSERT ... ON DUPLICATE KEY UPDATE将不起作用) . 这是我最终使用的内容:
replace into last_recogs (id, hasher_id, hash_id, last_recog)
select l.* from
(select id, hasher_id, hash_id, [new_value] from last_recogs
where hasher_id in (select id from hashers where name=[hasher_name])
and hash_id in (select id from hashes where name=[hash_name])
union
select 0, m.id, h.id, [new_value]
from hashers m cross join hashes h
where m.name=[hasher_name]
and h.name=[hash_name]) l
limit 1;
3 回答
Jai是正确的,你应该使用
INSERT ... ON DUPLICATE KEY UPDATE
.请注意,您不需要在update子句中包含datenum,因为它是唯一键,因此不应更改 . 您需要包含表中的所有其他列 . 您可以使用VALUES()函数确保在更新其他列时使用正确的值 .
以下是使用适用于MySQL的
INSERT ... ON DUPLICATE KEY UPDATE
语法重写的更新:尝试使用this:
我有一种情况,我需要根据两个字段(两个外键)更新或插入表,我无法设置UNIQUE约束(因此INSERT ... ON DUPLICATE KEY UPDATE将不起作用) . 这是我最终使用的内容:
此示例来自我的一个数据库,输入参数(两个名称和一个数字)替换为[hasher_name],[hash_name]和[new_value] . 嵌套的SELECT ... LIMIT 1拉出现有记录中的第一个或新记录(last_recogs.id是自动增量主键),并将其用作REPLACE INTO的值输入 .