我遇到一种情况,我需要根据无法设置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;
这个示例来自我的一个数据库,其中输入参数(两个名称和一个数字)被替换为[hasher_name],[hash_name]和[new_value]。嵌套的SELECT ... LIMIT 1拉取现有记录或新记录中的第一个(last_recogs.id是自动增量主键),并将其用作输入到REPLACE INTO中的值。