Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreign key referencing its own table?

Can any one explain why the following doesn't work on MySql (gives Syntax error currently):

create table manager
(
    employee_name varchar(20) not null,
    manager_name varchar(20) not null, 
    primary key employee_name, 
    foreign key (manager_name) references manager 
    on delete cascade
) 

also, assuming it did work, what would happen when a tuple in the relation manager is deleted?

like image 826
rrazd Avatar asked Dec 13 '25 05:12

rrazd


1 Answers

the syntax would be,

create table manager 
( 
    employee_name varchar(20) not null, 
    manager_name varchar(20) null, 
    CONSTRAINT tb_pk primary key (employee_name), 
    CONSTRAINT tb_fk foreign key (manager_name) 
          references manager (employee_name) on delete cascade 
)

QUESTIONS: assuming it did work, what would happen when a tuple in the relation manager is deleted?

ANSWER: all the child entries will also be deleted.

like image 96
John Woo Avatar answered Dec 14 '25 18:12

John Woo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!