Home > front end >  How do I check the integrity of a relationship in MySQL?
How do I check the integrity of a relationship in MySQL?

Time:01-24

I do something like this:

SET foreign_key_checks = 0;
//many different operations on several tables
SET foreign_key_checks = 1;

How can I verify that my entire base is consistent? I want to be sure that all relationships are properly maintained. For example, if I delete a "country" with id: 20, I want to make sure that no "city" has a non-existent relationship "country_id" = 20.

CodePudding user response:

It's easier if you do not SET foreign_key_checks = 0. If you keep the constraint enforcement on, then you can't make inconsistencies or broken references. You get an error if you try. So you should consider not turning off the FK checks if referential integrity is important.

If you do think you have inconsistencies, you must do a query like the following to verify there are no "orphans" that reference a parent that no longer exists:

SELECT cities.city_id
FROM cities
LEFT OUTER JOIN countries
 ON cities.country_id = countries.country_id
WHERE countries.country_id IS NULL;

If the JOIN condition was based on equality of country_id, this means country_id must not be NULL. The left outer join returns NULL for all columns when there is no match. So if you search in the WHERE clause for cases where country_id IS NULL this will only return cities that have no match in the other table.

You must do a separate query for each relationship in your database. This can be quite a chore, and if the tables are very large, it can take a long time.

I once had to do this many years ago in a buggy application that had no foreign key constraints (it used MyISAM tables). I ran a script to do all these orphan-checks every night, and eventually it grew to dozens of queries, and took hours to run.

Then comes the part that is even harder: once you do find some orphaned records, what do you do about them? Do you delete the orphans? Do you change their foreign key column to reference a parent record that does still exist? Do you restore the parent record? It could be any of these options, and you must have the orphaned records reviewed case by case, by someone with the knowledge and authority to choose how to resolve the issue.

It's far better to keep the constraints enforced so you don't have to do that work.

  •  Tags:  
  • Related