开发者

How to alter a table to add a self join relation?

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开发者_Go百科 in mysql without dropping the table.


alter table Users add constraint parent foreign key (ParentId) references
  Users (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:

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;


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);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜