How to update (change from first select table value second) second_table.first_table_id if first_table.email match in both select.
If it even possible. With one query!
—————————————– UPDATE —————————————–
EXAMPLE:
I need to update foreign key of second table if email field match in first table. I need to compare two query results with different parent_id (parents are in in same table with children)
table_1
-------------------------
| id | parent_id | email |
-------------------------
1 NULL NULL
2 NULL NULL
3 1 joe@m.ru
4 2 bob@f.ly
5 1 bob@f.ly
6 2 kira@.us
table_2
----------------
| id | first_id |
----------------
1 3
2 4
3 5
4 6
-
I have two parents with ids 1 and 2 and some children (ids: 3,4,5,6).
-
Also, keep in mind: 1 – old, 2 – new
-
Task: change foreign key in second table if children email with
parent_id = 1and chilren email withparent_id = 2match (are the same). -
In our example in second table row with
id = 3its foreign key field – first_id has to change from 5 to 4.
Following might get you started
Test script (SQL Server)
Output