简体   繁体   English

将table2中每个元素的值添加到table1中,并将table1中的MAX(id)+1用作table2 id

[英]Add values to table1 for each element from table2 and using MAX(id) + 1 from table1 as table2 id

I have table1 and table2 and want to do something like the following: 我有table1table2并想要执行以下操作:

INSERT INTO table1 (ID, OWNER_ID, NAME) SELECT (SELECT MAX(ID) FROM table1) + 1, ID, 'value' FROM table2

The query above does not work and returns: 上面的查询不起作用,并返回:

Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.table1(ID)"; SQL statement:

Any help please? 有什么帮助吗?

table1 : table1

| ID | OWNER_ID | NAME |
| --- | ---- | --- |

ŧable2 : ŧable2

| ID | OWNER_ID_REF | NAME |
| --- | ---- | --- |

Thanks 谢谢

set @i:=(SELECT MAX(ID) FROM table1);
INSERT INTO table1 (ID, OWNER_ID, NAME) SELECT @i:=@i+1, ID, 'value' FROM table2

try this query it will work fine 试试这个查询,它将正常工作

It looks like ID is a primary key column in table1 . 看起来IDtable1的主键列。 Your current insert will most likely be inserting the same ID value multiple times, because the max subquery will have the same value for each record in table2 . 您当前的插入很可能会多次插入相同的ID值,因为max子查询对于table2每个记录将具有相同的值。 Assuming ID is auto increment, you probably should not be assigning a value to it anyway. 假设ID是自动递增的,那么您可能始终不应该为其分配值。 Here is one option: 这是一个选择:

INSERT INTO table1 (OWNER_ID, NAME)
SELECT ID, 'value'
FROM table2;

You are using SELECT (SELECT MAX(ID) FROM table1) + 1, ID, 'value' FROM table2 您正在使用SELECT(SELECT MAX(ID)FROM table1)+ 1,ID,'value'FROM table2

When you are inserting Through select Max(ID)+1 give sample value all the records for table2 插入时,通过select Max(ID)+1给出表2的所有记录的样本值

Use something like this... 使用这样的东西...

Create table #tt( id int primary key ,Name varchar(200)) 创建表#tt(id int主键,名称varchar(200))

declare @vaue int = (select max(id) from #tt) 声明@vaue int =(从#tt选择max(id))

insert into #tt select row_number() over(order by id) + @vaue ,Name from #tt 插入#tt中,选择row_number()over(按ID排序)+ @vaue,从#tt中选择名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM