One for many with one table

I am trying to create a one-to-one relationship using a single table. Is it possible?

create table user(id int primary key auto_increment not null,                                                                                                                      
created_by int default null                                                                                                                                                        
)ENGINE=INNODB;                                                                                                                                                                    

alter table user add foreign key (created_by) references user(id) ON DELETE SET NULL ON UPDATE CASCADE;                                                                            

insert into user (id) VALUES(1);                                                                                                                                                   
insert into user (id, created_by) VALUES (2,1);   

Now, when I delete the user with id = 1, the created_by value is automatically reduced to NULL, as I expected.

But when I change the user id with id = 1, I get this error

mysql> update user set id=2 where id=1;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`jrt`.`user`, CONSTRAINT `user_ibfk_1` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE)

How can i fix this? Apply this update. I want the created_by column to be cascaded.

+5
source share
1 answer

, "". , 2 1. .

, . , . , ( ), .

[ ] ( ) . http://www.deeptraining.com/litwin/dbdesign/FundamentalsOfRelationalDatabaseDesign.aspx

- ", ".

, SQL Relational Basics, , ( ), ( , ) / ( , ).

; , . , " " , . , , , , , .

: , " " . SQL ( ). , .

: ". "

: http://forums.mysql.com/read.php?136,391782,391782

+2

All Articles