更新在 Oracle 中插入重复的主键?

UPDATE on INSERT duplicate primary key in Oracle?(更新在 Oracle 中插入重复的主键?)
本文介绍了更新在 Oracle 中插入重复的主键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 INSERT 查询,当主键重复时,我需要使用 UPDATE 代替.在 MySQL 中这似乎更容易,在 Oracle 中似乎我需要使用 MERGE.

I have a simple INSERT query where I need to use UPDATE instead when the primary key is a duplicate. In MySQL this seems easier, in Oracle it seems I need to use MERGE.

我能找到的所有 MERGE 示例都有某种源"和目标"表,在我的例子中,源和目标是同一个表.我无法理解这些示例来创建自己的查询.

All examples I could find of MERGE had some sort of "source" and "target" tables, in my case, the source and target is the same table. I was not able to make sense of the examples to create my own query.

MERGE 是唯一的方法还是有更好的解决方案?

Is MERGE the only way or maybe there's a better solution?

INSERT INTO movie_ratings
VALUES (1, 3, 5)

基本上就是这样,主键是前两个值,所以更新应该是这样的:

It's basically this and the primary key is the first 2 values, so an update would be like this:

UPDATE movie_ratings
SET rating = 8
WHERE mid = 1 AND aid = 3

我想使用一个触发器,它会在调用 INSERT 时自动执行 UPDATE 语句,但前提是主键是重复的.这样做有什么问题吗?我需要一些关于触发器的帮助,因为我在尝试理解它们并自己做时遇到了一些困难.

I thought of using a trigger that would automatically execute the UPDATE statement when the INSERT was called but only if the primary key is a duplicate. Is there any problem doing it this way? I need some help with triggers though as I'm having some difficulty trying to understand them and doing my own.

推荐答案

MERGE 是标准 SQL 中的根据需要执行 INSERT 或 UPDATE"语句,因此在 Oracle SQL 中也可能如此.

MERGE is the 'do INSERT or UPDATE as appropriate' statement in Standard SQL, and probably therefore in Oracle SQL too.

是的,您需要一个表"来合并,但您几乎可以肯定地动态创建该表:

Yes, you need a 'table' to merge from, but you can almost certainly create that table on the fly:

 MERGE INTO Movie_Ratings M
       USING (SELECT 1 AS mid, 3 AS aid, 8 AS rating FROM dual) N
          ON (M.mid = N.mid AND M.aid = N.aid)
       WHEN     MATCHED THEN UPDATE SET M.rating = N.rating
       WHEN NOT MATCHED THEN INSERT(  mid,   aid,   rating)
                             VALUES(N.mid, N.aid, N.rating);

(语法未验证.)

这篇关于更新在 Oracle 中插入重复的主键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
SQL to Generate Periodic Snapshots from Transactions Table(用于从事务表生成定期快照的SQL)
Inserting NaN value into MySQL Database(将NaN值插入MySQL数据库)
How to get insertId for MySQL using Mysql2 in Node with async and pool?(如何在带异步和池的Node中使用Mysql2获取MySQL的InsertID?)
MyBatis support for multiple databases(MyBatis支持多个数据库)
Oracle 12c SQL: Missing column Headers in result(Oracle 12c SQL:结果中缺少列标题)