Click here to Skip to main content
15,887,776 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Greetings guys, ive stumbled upon a tricky problem here, i want to achieve this in under 1 command text, imaginee i have a table_a with some template data so i can fill table_b with said template data and 2 more column referencing the IDs as parameters, for example:

SQL
SET @Last_ID=LAST_INSERTED_ID(); INSERT INTO table_a (col1, col2, col3) SELECT (col1,@Last_ID, col3) FROM table_b;



Is this sort of thing even achievable?
Please leave comment below if you guys need more clarifications.
Best Regards,
Eugen.

What I have tried:

I know i can do it by 2 separate commands, get all the data from table_b into program into some datatable and then inserting the data into table_a by spamming the insert clause per line example:
SQL
SELET col1, col2 from table_b WHERE col3=@col3ParameterValue;
Insert into table_a (col1, col2, col3) Values (@col1_1, @col2_1, @col3_1), (@col1_2, @col2_2, @col3_2), (@col1_3, @col2_3, @col3_3), (@col1_4, @col2_4, @col3_4), (@col1_5, @col2_5, @col3_5), (@col1_6, @col2_6, @col3_6), (@col1_7, @col2_7, @col3_7), (@col1_8, @col2_8, @col3_8), (@col1_9, @col2_9, @col3_9)...

but this is unneficient and i do not want to resort to this method.
Posted
Updated 13-Jul-16 1:18am
v3
Comments
ZurdoDev 12-Jul-16 12:20pm    
MySql syntax may be a little different, but Microsoft Sql would just be:

INSERT INTO ...
SELECT tbla.field1, tbla.field2, @someValue, @someOtherValue ...
FROM tbla...
Eugen_M 12-Jul-16 12:25pm    
Sorry i had a error with the text of the question, i updated it now.
ZurdoDev 12-Jul-16 12:28pm    
I don't see an error.
Eugen_M 12-Jul-16 12:31pm    
So youre saying it would go like:

INSERT INTO table_a
SELECT table_b.col1, @Last_ID, table_b.col1,
FROM table_b WHERE table_b.col3=@some_Other_Parameter;

is this the correct sintax?

Thanks in advance
ZurdoDev 12-Jul-16 12:44pm    
That should work. I would suggest that you specify your columns that you are insert into though. Again, this may not be exact syntax for MySql but in MSSql it works:

INSERT INTO table_a (col1, col2, col3)
SELECT table_b.col1, @Last_ID, table_b.col2
FROM table_b
WHERE table_b.col3=@some_Other_Parameter

1 solution

As mentioned in the comments, I would suggest that you specify your columns that you are inserting into. This may not be exact syntax for MySql but in MSSql it works:

SQL
INSERT INTO table_a (col1, col2, col3)
SELECT table_b.col1, @Last_ID, table_b.col2
FROM table_b
WHERE table_b.col3=@some_Other_Parameter
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900