如何在现有MySQL数据库中添加表之间的关系?
我有一个现有的 MySQL 数据库,其中包含大量表。
但问题是表之间的关系还没有添加。如何在现有 MySQL 数据库中的表之间添加关系?
I have a existing MySQL database which has large number of tables.
But the problem is the relationships between the tables has not been added. How can I add relationships between tables in my existing MySQL database?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
像这样的东西
something like this
其他人已经为您提供了如何在 SQl 代码中实现约束的答案。但最大的问题在于,由于您还没有这个约束,所以您现在可能不具有数据完整性。
首先,您确定哪些记录不满足约束。接下来,您决定如何处理它们并修复它们,删除它们或您决定的任何内容。然后,一旦数据干净,您就创建约束。
如果您已经有错误的数据,有时您能做的最好的事情就是添加“未知”的父记录,并附加所有没有现有父记录的子记录。例如,如果这些是附加了财务价值的实际订单您不想删除它们(这会扰乱财务报告),然后您使用“未知客户”。
假设您想添加一个字段或整个记录,则可能会出现其他情况。链接到以地址表为子项的状态表假设现在它的状态为 107,而您的状态 id 不是 107。最好有一个根本无法使用的地址(例如,您不能邮寄到状态未知),因此删除记录或将州字段留空(因为您的用户可以联系客户并填写该记录,并且您有一个不想丢失的街道地址。
只有您可以决定您的特定应用程序及其用途了解如何处理当前不良记录。而且由于你现在没有任何限制,所以你有不良记录的可能性非常高。
Others have given you the answer as to how implement a constraint in SQl code. but the biggest problme lies in the fact that since you didn't have this constraint already, you may not now have data integrity.
First you identify which records would not meet the constraint. Next you decide what to do about them and fix them, delete them or whatever you decide. Then you create the constraint once the data is clean.
If you already have bad data sometimes the best you can do is add a parent record for "unknown' and attach all the child records that do not have an existing parent to it. For instance if these were actual orders that had financial values attached to them you wouldn't want to delete (that messes up financial reporting) them and then you use the Unknown Customer.
There might be other cases where you can safely delete the information in the field or the whole record. Suppose you wwanted to add a link to a state table with an address table as the child table. Suppose right now it has state 107 and you don't have a state id of 107. Is it better to have an address that can't be used at all (you can't mail to state Unknown for instance) and thus delete the record or to leave the state field blank (because your users can contact the customer and get it filled in and you have a street address you don't want to lose.
Only you can decide for your particular app and what it is used for how to handle currently bad records. And since you have no constraints now, the chances that you have bad records are very high.
来自 文档 添加的语法对现有表的外键约束是
From the docs The syntax for adding foreign keys constraints to existing tables is