Let's say we have two tables like this:
TableA TableB
ID CODE NAME ID A_ID OBJECT
1 200 Name1 1 1 Object1
2 #200 Name1 2 1 Object2
3 300 Name2 3 3 Object1
4 #300 Name2 4 3 Object2
In TableA
Name1
with code = 200
and Name1
with code = #200
are the same.
And the A_ID
from TableB
is foreign key in ID
in TableA
. In TableB
the same A_ID
appears many times. The task is to change the IDs in TableB like this - instead of the item with A_ID = 1
and CODE = 200
to change every row with the A_ID = 2
:
TableB
ID OBJECT
2 Object1
2 Object2
4 Object1
4 Object2
Until now I do that in separate statements like this:
SELECT * FROM TableA WHERE CODE LIKE '#%'; # this gives me the IDs that I need to change
SELECT * FROM TableA WHERE CODE NOT LIKE '#%'; # and this gives me the other IDs
After that I do JOIN
and UPDATE
on TableB like this:
SELECT t1.ID,t1.CODE,t2.ID,t2.OBJECT
FROM TableA t1
JOIN TableB t2 ON t1.ID = t2.A_ID; # to see on which IDs the record appears
UPDATE TableB SET A_ID = 2 WHERE ID = 1; # to change them one by one
I've read here that Firebird does not support JOIN
in UPDATE
statements. Is there a way to make this in one query?
EDIT: The main idea behind this is - Table B has to have IDs
only on items with CODE
that starts with #
from TableA
. For now it has both with and without. I did try using merge for all the records but can't understand how to get the desired IDs
pumped in TableB
.
MERGE INTO TableB as b
USING TableA as a
ON a.ID = b.A_ID AND CODE NOT LIKE '#%'
WHEN MATCHED THEN
# here I need a statement that updates the table with the IDs
of the items that have code starting with '#'