如何更改表以添加自连接关系?
我有一个名为“Users”的表,它包含一些字段,例如 Id、ParentId、Name。
我想要的是更改此表以添加新的自连接关系,以便 ParentId 链接到 Id,但 ParentId 可为空。 我想在mysql中编写这个alter sql语句而不删除表。
I have a table called "Users" it contain some fields such as Id, ParentId, Name.
What I want is to alter this table to add new self join relation so that ParentId link to Id, but ParentId is nullable.
I want to write this alter sql statment in mysql without dropping the table.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的意思是要添加外键约束吗?如果是这样,请参阅外键约束 文档。下面是一个示例,从创建一个简单的表开始:
为
parent_id
列添加索引:添加外键约束:
显示新的表结构:
Do you mean that you want to add a foreign key constraint? If so, see the FOREIGN KEY Constraints docs. Here's an example, starting with creating a simple table:
Add an index for the
parent_id
column:Add the foreign key constraint:
Show the new table structure:
请注意,如果您正在使用包含数据的表,并且存在孤立关系,则外键关系创建将会失败。在创建外键之前查找并修复孤儿!
SELECT * FROM
users
WHEREparent_id
NOT IN (SELECT ID FROMusers
);Note that if you're working with a table that contains data, foreign key relationship creation will fail if orphaned relationships exist. Find and fix orphans prior to creating foreign keys!
SELECT * FROM
users
WHEREparent_id
NOT IN (SELECT ID FROMusers
);