I want to insert values ​​from table1 to table2 with incremental value

I tried something like this, but the id value does not change, getting the value for the first record and setting the value for everything else ...

insert into table1 (Id,b,c,d) 
 (select (select max(Id)+1 from table1),x,y,z from table2 where... )
+3
source share
1 answer

Use a column. Then you can simply do this:

INSERT INTO table1 (b, c, d) 
SELECT x, y, z
FROM table2
WHERE ...

If you don't want to use a column with auto-increment, you can get the same effect by adding a row line number and not always adding 1. This syntax works in almost all major SQL databases (and not in MySQL, though):

INSERT INTO table1 (Id, b, c, d) 
SELECT 
    (SELECT MAX(Id) FROM table1) + ROW_NUMBER() OVER (ORDER BY x),
    x, y, z
FROM table2
WHERE ...
+6
source

Source: https://habr.com/ru/post/1743387/


All Articles