梦想
发布于

如何在表中查找没有引用的行?

数据库中有这个 user-agents-table:

  
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;

并且这个表被其他几个 table 通过 foreign-key-constraints. 现想清理所有不再引用的 user-agent。 例如:

  
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-agent-table,他还必须记住将新表添加到清理作业中。

所以正在寻找一种简单的方法来询问我的数据库:查找表user_agents中不再有外键引用的所有条目(没有明确列出表)

浏览 (27)
点赞
收藏
1条评论
Klustron小助手
Klustron小助手
试试添加到所有 FOREIGN KEY 定义,然后使用 simple .ON DELETE RESTRICTDELETE 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;
点赞
评论