我的数据库中有这个用户代理表:
CREATE TABLE user_agents (
pk bigint NOT NULL AUTO_INCREMENT,
user_agent TEXT NOT NULL,
user_agent_hash BINARY(16) UNIQUE NOT NULL,
PRIMARY KEY (pk),
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_as_cs;
并且该表被其他几个表通过外键约束引用。 现在我想清理所有不再引用的用户代理。 我当然可以这样做:
SELECT pk
FROM user_agents ua
LEFT JOIN table_1 t1 ON ua.pk = t1.user_agent_fk
LEFT JOIN table_2 t2 ON ua.pk = t2.user_agent_fk
LEFT JOIN table_3 t3 ON ua.pk = t3.user_agent_fk
LEFT JOIN table_4 t4 ON ua.pk = t4.user_agent_fk
WHERE t1.pk IS NULL
AND t2.pk IS NULL
AND t3.pk IS NULL
AND t4.pk IS NULL;
但这看起来非常丑陋,如果有人添加 table_5(也引用了用户代理表),他还必须记住将新表添加到清理作业中。
所以我正在寻找一种简单的方法来询问我的数据库:查找表 user_agents 中不再有外键引用的所有条目(无需显式列出表)
将
ON DELETE RESTRICT
添加到所有外键定义,然后使用简单的 DELETE IGNORE
。
CREATE TABLE main (id INT PRIMARY KEY)
SELECT 1 id UNION SELECT 2 UNION SELECT 3 UNION SELECT 4;
CREATE TABLE slave1 (id INT, FOREIGN KEY (id) REFERENCES main (id) ON DELETE RESTRICT);
INSERT INTO slave1 SELECT 1 id UNION SELECT 2;
CREATE TABLE slave2 (id INT, FOREIGN KEY (id) REFERENCES main (id) ON DELETE RESTRICT);
INSERT INTO slave2 SELECT 2 id UNION SELECT 4;
SELECT * FROM main;
id |
---|
1 |
2 |
3 |
4 |
DELETE IGNORE FROM main;
SELECT * FROM main;
id |
---|
1 |
2 |
4 |