如何更改表以添加自连接关系?

发布于 2024-09-17 05:05:35 字数 141 浏览 1 评论 0原文

我有一个名为“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

恋竹姑娘 2024-09-24 05:05:35
alter table Users add constraint parent foreign key (ParentId) references
  Users (Id);
alter table Users add constraint parent foreign key (ParentId) references
  Users (Id);

您的意思是要添加外键约束吗?如果是这样,请参阅外键约束 文档。下面是一个示例,从创建一个简单的表开始:

CREATE TABLE `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `parent_id` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

parent_id 列添加索引:

ALTER TABLE users
ADD INDEX `parent_id` (`parent_id`);

添加外键约束:

ALTER TABLE users
ADD CONSTRAINT `fk_parent_id`
FOREIGN KEY `parent_id` (`parent_id`)
REFERENCES `users` (`id`);

显示新的表结构:

SHOW CREATE TABLE users;

CREATE TABLE `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `parent_id` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `parent_id` (`parent_id`),
  CONSTRAINT `fk_parent_id`
    FOREIGN KEY (`parent_id`)
    REFERENCES `users` (`id`)
) ENGINE=InnoDB;

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:

CREATE TABLE `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `parent_id` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

Add an index for the parent_id column:

ALTER TABLE users
ADD INDEX `parent_id` (`parent_id`);

Add the foreign key constraint:

ALTER TABLE users
ADD CONSTRAINT `fk_parent_id`
FOREIGN KEY `parent_id` (`parent_id`)
REFERENCES `users` (`id`);

Show the new table structure:

SHOW CREATE TABLE users;

CREATE TABLE `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `parent_id` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `parent_id` (`parent_id`),
  CONSTRAINT `fk_parent_id`
    FOREIGN KEY (`parent_id`)
    REFERENCES `users` (`id`)
) ENGINE=InnoDB;
待"谢繁草 2024-09-24 05:05:35

请注意,如果您正在使用包含数据的表,并且存在孤立关系,则外键关系创建将会失败。在创建外键之前查找并修复孤儿!

SELECT * FROM users WHERE parent_id NOT IN (SELECT ID FROM users);

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 WHERE parent_id NOT IN (SELECT ID FROM users);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文