使用单个查询在mysql中插入update delete

时间:2022-11-28 01:32:02

I have two table source and target. Is it possible to perform following operation in single query?

我有两个表源和目标。是否可以在单个查询中执行以下操作?

  • If the row exists in both the source and target, UPDATE the target;

    如果源和目标中都存在该行,则更新目标;

  • If the row only exists in the source, INSERT the row into the target;

    如果该行仅存在于源中,则将该行插入目标;

  • If the row exists in the target but not the source,
    DELETE the row from the target.

    如果行存在于目标中但不存在于源中,则从目标中删除该行。

1 个解决方案

#1


2  

You can't do it all in one query, but you can do it all in one transaction if you are using a transactional store engine (like InnoDB). This might be what you want,

您无法在一个查询中完成所有操作,但如果您使用的是事务存储引擎(如InnoDB),则可以在一个事务中完成所有操作。这可能是你想要的,

START TRANSACTION;

INSERT...; DELETE... UPDATE...;

插...;删除...更新...;

COMMIT;

#1


2  

You can't do it all in one query, but you can do it all in one transaction if you are using a transactional store engine (like InnoDB). This might be what you want,

您无法在一个查询中完成所有操作,但如果您使用的是事务存储引擎(如InnoDB),则可以在一个事务中完成所有操作。这可能是你想要的,

START TRANSACTION;

INSERT...; DELETE... UPDATE...;

插...;删除...更新...;

COMMIT;