我需要在表中更新日期值,如果它不存在则必须插入
在MySql中执行此操作的最佳方法是什么
目前我正在使用
SELECT Id INTO LId FROM ATABLE WHERE ID = FID;
IF LId IS NULL THEN
INSERT INTO ATABLE(abc) Values (2)
ELSE
UPDATE ATABLE Set Abc = 2 Where Id = LId
END IF;
但这会使数据库遭遇3次
有更好的方法吗?
答案 0 :(得分:5)
答案 1 :(得分:3)
Here如果你需要的话。
答案 2 :(得分:3)
对于MySql Upsert,您可能需要查看此blog post。它强调了一些方法,包括进行更新,然后使用左连接进行插入:
update t1 as l
inner join t2 as r on l.a = r.d
set l.b = r.e, l.c = r.f;
insert into t1 (a, b, c)
select l.d, l.e, l.f
from t2 as l
left outer join t1 as r on l.d = r.a
where r.a is null;
使用ON DUPLICATE KEY UPDATE:
可以进行单个语句upsertinsert into t1(a, b, c)
select d, e, f from t2
on duplicate key update b = e, c = f;