You're managing a set of InnoDB tables that undergo periodic updates involving row deletion and insertion. These tables have foreign key constraints, making the order of table loading crucial. To avoid foreign key constraint issues, you rely on disabling and re-enabling foreign key checks (SET FOREIGN_KEY_CHECKS=0 and SET FOREIGN_KEY_CHECKS=1). However, you find that loading data with the checks disabled doesn't trigger any warnings or errors when you re-enable them, despite intentionally violating foreign key rules.
InnoDB does not provide a direct way to force a foreign key check, but there are workarounds.
One approach is to create a stored procedure (ANALYZE_INVALID_FOREIGN_KEYS) that examines all foreign keys in a database and identifies any that are violated. The procedure loops through foreign keys, generates queries to check for invalid references, and stores the results in a temporary table.
DELIMITER $$ DROP PROCEDURE IF EXISTS ANALYZE_INVALID_FOREIGN_KEYS$$ CREATE PROCEDURE `ANALYZE_INVALID_FOREIGN_KEYS`( checked_database_name VARCHAR(64), checked_table_name VARCHAR(64), temporary_result_table ENUM('Y', 'N')) LANGUAGE SQL NOT DETERMINISTIC READS SQL DATA BEGIN -- ... (procedure implementation) END$$ DELIMITER ;
To use the procedure, provide three parameters:
The procedure loads the results into a temporary or permanent table named INVALID_FOREIGN_KEYS. This table contains information about invalid foreign keys, including the table schema, table name, column name, constraint name, referenced table schema, referenced table name, referenced column name, count of invalid keys, and a SQL query to retrieve the invalid rows.
To check for invalid foreign keys in all databases:
CALL ANALYZE_INVALID_FOREIGN_KEYS('%', '%', 'Y');
To view the results:
SELECT * FROM INVALID_FOREIGN_KEYS;
To retrieve the invalid rows for a specific foreign key, execute the corresponding INVALID_KEY_SQL query from the INVALID_FOREIGN_KEYS table.
This approach requires indexes on both the referring and referred columns for optimal performance.
The above is the detailed content of How to Force Foreign Key Checks in InnoDB Tables When `SET FOREIGN_KEY_CHECKS=1` Fails to Trigger Warnings or Errors?. For more information, please follow other related articles on the PHP Chinese website!