Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Update after Joining Two Tables

Tags:

sql-server

I am new to SQL, using Microsoft SQL Server Management Studio.

I am trying to write a SQL statement that performs an update after two tables are joined.

I have two tables: myTable1 and myTable2. Both share a field MyID, which is going to be the field that I join on. myTable1 contains a column called BitToUpdate. And MyTable2 contains a column called BitToCheck.

I want to set BitToUpdate in myTable1 to be 1 where BitToCheck in myTable2 is 1 as well.

Here is what I have:

SELECT M.MyID, BitToUpdate, BitToCheck
INTO #temp_table
FROM myTable1 as T1
LEFT JOIN myTable2 as T2
ON M.MyId = PO.MyId

So first I tried to join the two tables myTable1 and myTable2 on their IDs, and store the result in a temporary table.

Next, I want to update BitToUpdate to be 1 where BitToCheck is 1.

So to do that in the temporary table, I have:

UPDATE #temp_table
SET 
    `BitToUpdate` = 1
WHERE
    `BitToCheck` = 1

This updates the BitToUpdate successfully in #temp_table. However, when I do a select on myTable1, I find that BitToUpdate is not changed. I suppose this makes sense as #temp_table isn't really a "pointer"....

But what would be the correct way to approach this join and update?

like image 939
Rhs Avatar asked Mar 18 '13 16:03

Rhs


People also ask

Can we update a table using join in SQL?

SQL UPDATE JOIN could be used to update one table using another table and join condition. UPDATE tablename INNER JOIN tablename ON tablename.

How use multiple tables in SQL update with 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.

Can we use inner join in update statement?

We use the Set statement for specifying the values. Use SQL Join operator and specify the table name with join conditions. We can either use an Inner Join or Left Join in this predicate. Add Where clause to update only specific rows.


2 Answers

You don't need to use a LEFT JOIN here, since you are checking on a condition from table 2, so an INNER JOIN should be better here.

UPDATE T1
SET T1.BitToUpdate = 1
FROM myTable1 T1
INNER JOIN myTable2 T2
    ON T1.MyId = T2.MyId
WHERE T2.BitToCheck = 1
like image 78
Lamak Avatar answered Nov 15 '22 21:11

Lamak


What you are doing in your first query is updating a temp table named #temp. the updates never go to the actual table myTable1 or mayTable2. To update records while joining with other tables try this:

UPDATE T1
SET T1.BitToUpdate = 1
FROM myTable1 as T1
LEFT JOIN myTable2 as T2 (ON T1.MyId = T2.MyId)
WHERE T2.BitToCheck = 1
like image 42
Mortalus Avatar answered Nov 15 '22 23:11

Mortalus