识别 MySQL 数据库中未在创建数据库时定义的 FK?
Identifying FK's in a MySQL database that were not defined upon database creation?
数据库已用 5 table 秒创建。这些 table 在创建时填充了数据 - 可能是从以前的数据库导入的。
创建数据库时,为每个 table 创建了主键,但没有创建外键。
我如何 运行 查询来识别哪些 table 列包含与其他 table 中的 PK 相关的数据?实际上,我如何识别每个 table 上的 FK 列?某些 table 可能包含 2 个 FK。
最终目标是识别每个 table 中的 FK('s) 并使用适当的 FK 结构和 table 关系正确设置 table。
不要尝试使用查询来自动执行此数据库设计/reverse-engineering 过程。 (如果你有 500 个 table,也许吧。但你只有五个。)
关注您的 table 定义。例如,如果您的 user
table 中有一个 id
主键列,您的 contact
table 可能有一个 user_id
列。那是 user.id
的 FK。如果您真正了解您的 table 是如何与 FK 联系在一起的,这将对您有很大帮助。
并且请记住,如果您不费心实际声明这些外键,您的系统仍然可以正常运行。你会失去什么:
- 约束,其中数据库引擎阻止,例如
contact.user_id
列值不指向任何 user.id
行。
- 可能有一些有用的索引。
MySql Workbench has a reverse engineering feature. It inspects the definition of a database and does its best to sort out various entities (tables) and the relationships (foreign key dependencies) between them. It presents graphical e:r diagrams and can generate DDL。这可以帮助您了解数据库并设置适当的 FK。但是,请检查它建议的关系:此数据是您的,而不是 Workbench 的。
数据库已用 5 table 秒创建。这些 table 在创建时填充了数据 - 可能是从以前的数据库导入的。
创建数据库时,为每个 table 创建了主键,但没有创建外键。
我如何 运行 查询来识别哪些 table 列包含与其他 table 中的 PK 相关的数据?实际上,我如何识别每个 table 上的 FK 列?某些 table 可能包含 2 个 FK。
最终目标是识别每个 table 中的 FK('s) 并使用适当的 FK 结构和 table 关系正确设置 table。
不要尝试使用查询来自动执行此数据库设计/reverse-engineering 过程。 (如果你有 500 个 table,也许吧。但你只有五个。)
关注您的 table 定义。例如,如果您的 user
table 中有一个 id
主键列,您的 contact
table 可能有一个 user_id
列。那是 user.id
的 FK。如果您真正了解您的 table 是如何与 FK 联系在一起的,这将对您有很大帮助。
并且请记住,如果您不费心实际声明这些外键,您的系统仍然可以正常运行。你会失去什么:
- 约束,其中数据库引擎阻止,例如
contact.user_id
列值不指向任何user.id
行。 - 可能有一些有用的索引。
MySql Workbench has a reverse engineering feature. It inspects the definition of a database and does its best to sort out various entities (tables) and the relationships (foreign key dependencies) between them. It presents graphical e:r diagrams and can generate DDL。这可以帮助您了解数据库并设置适当的 FK。但是,请检查它建议的关系:此数据是您的,而不是 Workbench 的。