SQL 甲骨文数据库。将行的副本插入同一个表(重复键错误消息)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20907770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Oracle Database. Insert a copy of a row to the same table (Duplicate key error message)
提问by Mark2
In Oracle database I have one table with primary key GAME_ID. I have to insert a copy of a row where game_name = 'Texas holdem' but it tells me:
在 Oracle 数据库中,我有一个带有主键 GAME_ID 的表。我必须插入一个行的副本,其中 game_name = 'Texas Holdem' 但它告诉我:
An UPDATE or INSERT statement attempted to insert a duplicate key.
UPDATE 或 INSERT 语句试图插入重复的键。
This is query I am using:
这是我正在使用的查询:
INSERT INTO GAME (SELECT * FROM GAME WHERE NAME = 'Texas Holdem');
回答by a_horse_with_no_name
Assuming your game_id
is generated by a sequence, you can get a new as part of the select statement:
假设你game_id
是由一个序列生成的,你可以得到一个 new 作为 select 语句的一部分:
INSERT INTO GAME (game_id, name, col_3)
SELECT seq_game_id.nextval, name, col_3
FROM GAME
WHERE NAME = 'Texas Holdem';
回答by Branko Dimitrijevic
Let me just offer a slightly more abstract point of perspective...
让我提供一个稍微抽象一点的观点......
- In a relational database, table is a physical representation of the mathematical concept of relation.
- Relation is a set(of tuples, i.e. table rows/records).
- A set either contains given element or it doesn't, it cannot contain the same element multiple times (unlike multiset).
- Therefore, you can never have two identical rows in the table, and still call your database "relational".1
- 在关系数据库中,表是关系数学概念的物理表示。
- 关系是一组(元组,即表行/记录)。
- 一个集合要么包含给定的元素,要么不包含,它不能多次包含相同的元素(与多重集不同)。
- 因此,您永远不能在表中有两个相同的行,并且仍然称您的数据库为“关系”。1
You can insert a similarrow through, as other answers have demonstrated.
正如其他答案所展示的那样,您可以插入一个类似的行。
1Although practical DBMS (including Oracle) will typically allow you to create a table without any key, making identical duplicates physically possible. However, consider it a big red flag if you ever find yourself doing that.
1虽然实用的 DBMS(包括 Oracle)通常允许您创建一个没有任何键的表,但在物理上可能会出现相同的重复项。但是,如果您发现自己这样做,请将其视为一个很大的危险信号。
回答by usr
You can only have one row with the same key. Don't duplicate the key. Specify the list of columns you want to copy and leave the key out (assuming it is provided automatically).
您只能有一行具有相同的键。不要复制密钥。指定要复制的列列表并保留键(假设它是自动提供的)。
回答by Dylan
You try to insert a row already in your table. So for example in your table you have
您尝试在表中插入一行。因此,例如在您的表中,您有
GAME_ID Name
1 Texas Holdem
You try to insert into your table this line, but the game_id 1 is already there So if you want to insert this, you need to create a new line like this in order to generate a new game_id for this game name :
您尝试将此行插入到您的表中,但 game_id 1 已经存在所以如果您想插入它,您需要像这样创建一个新行,以便为这个游戏名称生成一个新的 game_id :
INSERT INTO GAME(Name) VALUES ('Texas Holdem')