Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a new column with data from a join

Tags:

What is the best approach to add a column to an existing table with values from a join...For example:

If I join Table A to Table B...

Select A.Column1, A.Column2, B.Column1, B.Column2, B.Column3 FROM A INNER JOIN B ON A.Column1 = B.Column2 

Basically I just want to copy the column that exists in Table B over to Table A, how can I add new A.Column3 to Table A to match B.Column3 based on the join?

like image 455
dorianpc Avatar asked Nov 11 '11 17:11

dorianpc


People also ask

Can you UPDATE a table with a join?

To UPDATE a table by joining multiple tables in SQL, let's create the two tables 'order' and 'order_detail. ' We can update the data of a table using conditions of other joined tables. It is possible to join two or more tables in an UPDATE query.

How do you create a new column in SQL based on another column?

In Microsoft SQL Server, we can change the order of the columns and can add a new column by using ALTER command. ALTER TABLE is used to add, delete/drop or modify columns in the existing table. It is also used to add and drop various constraints on the existing table.


2 Answers

Try this:

alter table A add column3 datatype  update A  set column3 = B.column3  from A inner join B on A.Column1 = B.Column2 
like image 153
Steve Henderson Avatar answered Oct 07 '22 01:10

Steve Henderson


Note that this is probably not most efficient method

alter table A add column3 [yourdatatype];  update A set column3 = (select column3 from B where A.Column1 = B.Column2)    where exists (select column3 from B where A.Column1 = B.Column2) 
like image 45
bpgergo Avatar answered Oct 07 '22 00:10

bpgergo