簡體   English   中英

使用不同的密鑰將表中的數據復制到同一個表中

[英]Copy data from a table, into the same table with a different key

我很好奇是否有可能從表中獲取數據,並復制它但指定一個新的主鍵

例如,我希望獲取具有列“question_id”的數據,該列充當表的唯一鍵,並將具有該question_id的表中的所有數據復制到同一個表但使用新的question_id。

有關使用SQL是否可行的任何想法?

我的數據庫是一個ingres數據庫

提前致謝

當然,這樣的事情應該有效:

INSERT INTO YourTable (Question_Id, OtherField,...)
SELECT SomeNewQuestionId, OtherField,...
FROM YourTable
WHERE Question_Id = SomeQuestionId

只需用適當的值替換SomeQuestionIdSomeNewQuestionId

這是一個簡單的選擇查詢。

insert into mytable
 (field2, field3, etc)
select field2, field3, etc
from mytable
where whatever.

這假設字段2和3都不是主鍵,並且您有自動增量表。

快進兩年.... :)我認為這是最好和最簡單的方法。 使用主鍵從同一個表中插入一行數據將導致錯誤,因為主鍵對於每一行都是唯一的:讓question_id = 100。

INSERT INTO MyTable SELECT * FROM MyTable Where question_id=100;

在PostgreSQL中:

ERROR:  duplicate key value violates unique constraint "MyTable_pkey"
DETAIL:  Key (question_id)=(100) already exists.

避免重復鍵值非常簡單:

INSERT INTO MyTable SELECT (SELECT MAX(question_id)+1),Column1,Column2,etc FROM MyTable Where question_id=100;

通過使用MAX(question_id)+1,您將增加MyTable的question_id主鍵的最大值,然后將數據添加/復制到具有唯一question_id值的新行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM