Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert data into table with result from another select query

I am seeking help on the following issue: I have two tables Table_1 columns are itemid, locationid, quantity

Table_2 columns are itemid, location1, location2, location3

I want to copy data from Table_1 (only quantity column) into Table_2 (into location1 column). The itemid are same in both the tables(Table_1 has duplicate item id's) so that's the reason I want to copy to a new table and keep all quantity in one single row with each location as a column. I am using the below query but it doesn't work

INSERT INTO  Table_2(location1)  (  SELECT qty   FROM Table_1   WHERE locationid = 1 AND Table_1.locationid = Table_2.locationid ) 
like image 281
mmdel Avatar asked Jun 15 '11 06:06

mmdel


People also ask

How can I use one query result in another query?

Use the results of a query as a field in another query. You can use a subquery as a field alias. Use a subquery as a field alias when you want to use the subquery results as a field in your main query. Note: A subquery that you use as a field alias cannot return more than one field.

Can we use insert and select together?

In previous examples, we either specified specific values in the INSERT INTO statement or used INSERT INTO SELECT to get records from the source table and insert it into the destination table. We can combine both columns and defined values in the SQL INSERT INTO SELECT statement.


1 Answers

If table_2 is empty, then try the following insert statement:

insert into table_2 (itemid,location1)  select itemid,quantity from table_1 where locationid=1 

If table_2 already contains the itemid values, then try this update statement:

update table_2 set location1= (select quantity from table_1 where locationid=1 and table_1.itemid = table_2.itemid) 
like image 149
Aziz Shaikh Avatar answered Oct 14 '22 22:10

Aziz Shaikh