views:

16

answers:

2

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.

+2  A: 
alter table Users add constraint parent foreign key (ParentId) references
  Users (Id);
+1  A: 

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