I need to add a Foreign Key to a table that already exists and is populated with data that would contain invalid Foreign Key Values. (MYSQL)
I know there are several questions along these lines, but I can't seem to find any that answer my scenario.
Table and Data Structure
"GblTable" contains an "Org" field that needs to become a FK of the Org table. The Org table has a PK field called "number".
Currently, the GblTable contains non-existent Org numbers (ie. If the Org table has rows with PKs 1,2, and 3, GblTable might have rows with Org as 4 or 5). While this is the case, I cannot apply the constraint to reference GblTable.org to Org.number.
I believe the best approach for this particular situation will will be to set the FK field in those rows to NULL before I apply the constraint. NULL is a valid GblTable.Org value for the program, so this would achieve an acceptable outcome.
What I Have so Far
I want to set all GblTable.Org values to NULL where they do not match a valid Org.Number.
In pseudocode:
set GblTable.ORG to NULL
where the GblTable.number is one of the following:
( select all GblTable.numbers where the GblTable.Org does not match an existing Org.Number )
In Sql, but I get the error "You can't specify target table 'GblTable' for update in FROM clause":
update GblTable set Org=NULL
where number IN (
select number
from GblTable
where Org NOT IN (select number from Org)
)
What's the best way to achieve my requirement?