UPDATE with several records from another table

Asked

Viewed 682 times

1

I have a table T1 where I have the ID.
I have a table T2 where you take the ID_T1(Foreign Key) of T1.
I have a table T3 where you take the ID_T1(Foreign Key) of T1 and the ID_T2(Foreign Key) of T2.

On the table T3, the Ids of T1 are set, however, to T3 I created after these records were entered, IE, are with the column records ID_T2 to NULL. Is there any way I can make some UPDATE in T3, passing all the Ids of the T2 in the right way?

Below is the code I’m trying:

UPDATE  T3 
SET     T3.ID_T2 =  (
                        SELECT      T2.ID 
                        FROM        T2 
                        INNER JOIN  T3 ON T2.ID_T1 = T3.ID_T1
                    ) 
WHERE   T3.ID_T1 =  (
                        SELECT      T1.ID 
                        FROM        T1 
                        INNER JOIN  T3 ON T3.ID_T1 = T1.ID 
                        INNER JOIN  T2 ON T2.ID_T1 = T3.ID_T1
                    )

In SQL Server 2008.

  • If the goal is just to update the ID_T2 table T3, just remove the WHERE, I think this is how it works.

  • @Joãomartins So dude, apart from WHERE, he changes all the fields to the same ID, that’s not what I’m looking for.

  • Right, you’re absolutely right. New answer with code below.

1 answer

0


This query can solve your problem:

UPDATE      T3 
SET         T3.ID_T2 = T2.ID
FROM        T3
INNER JOIN  T1 ON T1.ID     = T3.ID_T1
INNER JOIN  T2 ON T2.ID_T1  = T1.ID

What it does is basically update the ID_T2 with the ID from the table T2, which in turn is associated with the table T1 for ID_T1.

  • So now it only changes one record. It’s only changing the last record of table T2.

  • So this may be related to the information that the 3 tables have. query but with SELECT instead of UPDATE?

  • So he brings me a line, referring to the data of the last record that was entered.

  • Okay, so on the table T3 there is only one record that has a link between the table T1 and the T2, since we’re calling them by INNER JOIN.

  • Actually, it now worked. It only had 1 record even related!

  • Perfect ;)! If you can mark the answer as correct, I would appreciate it!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.