Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update and left outer join statements

I have two tabels with a relation and I want to update a field in table A. Is it possible to combine update and join in the same query? I googled it but didnt find any working solution?

UPDATE md SET md.status = '3'  FROM pd_mounting_details AS md  LEFT OUTER JOIN pd_order_ecolid AS oe ON md.order_data = oe.id 

I'm using MS SQL

like image 536
Evilaid Avatar asked Jun 13 '11 19:06

Evilaid


People also ask

Can we use left join in UPDATE query?

SQL Server UPDATE JOIN syntax To query data from related tables, you often use the join clauses, either inner join or left join. In SQL Server, you can use these join clauses in the UPDATE statement to perform a cross-table update.

Can we use UPDATE with joins?

The most easiest and common way is to use join clause in the update statement and use multiple tables in the update statement. Here we can see that using join clause in update statement. We have merged two tables by the use of join clause.

What is left outer join with example?

A left outer join is a method of combining tables. The result includes unmatched rows from only the table that is specified before the LEFT OUTER JOIN clause. If you are joining two tables and want the result set to include unmatched rows from only one table, use a LEFT OUTER JOIN clause or a RIGHT OUTER JOIN clause.

Can you UPDATE 2 tables with a UPDATE statement in SQL?

In SQL Server, we can join two or more tables, but we cannot update the data of multiple tables in a single UPDATE statement.


2 Answers

Update t  SET         t.Column1=100 FROM         myTableA t  LEFT JOIN         myTableB t2  ON         t2.ID=t.ID 

Replace myTableA with your table name and replace Column1 with your column name.

After this simply LEFT JOIN to tableB. t in this case is just an alias for myTableA. t2 is an alias for your joined table, in my example that is myTableB. If you don't like using t or t2 use any alias name you prefer - it doesn't matter - I just happen to like using those.

like image 198
JonH Avatar answered Oct 02 '22 20:10

JonH


If what you need is UPDATE from SELECT statement you can do something like this:

UPDATE suppliers     SET city = (SELECT customers.city FROM customers  WHERE customers.customer_name = suppliers.supplier_name) 
like image 26
kleinohad Avatar answered Oct 02 '22 18:10

kleinohad