Question

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.

Was it helpful?

Solution

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;

OTHER TIPS

alter table Users add constraint parent foreign key (ParentId) references
  Users (Id);

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top