mysql - parent child table sql issue -
i have 3 tables below have many many relation...in student table have multiple foreign keys sec_id,ad_id dont know how add foreign key parent-child relation please me out..
create table student( s_id int auto_increment, name varchar(30) not null, primary key(s_id) ) create table section( sec_id int auto_increment, name varchar(2) not null, primary key(sec_id) ) create table advisor( ad_id int auto_increment, name varchar(2) not null, primary key(ad_id) )
if student can have @ one advisor, it's one-to-many relationship.
the normal pattern implementing relationship define foreign key column in child table, table on "many" side of relationship. example:
alter table student add ad_id int comment 'fk ref advisor'; further, storage engines, innodb, support , enforce foreign keys. is, can have database enforce restrictions (constraints) on values can stored in columns defined foreign keys.
for example, can establish rule says value stored in ad_id column in student table... must found in row in advisor table, in ad_id column.
for example:
alter table student add constraint fk_student_advisor foreign key (ad_id) references advisor(ad_id) on delete restrict on update cascade this enforces rule row advisor table cannot deleted if there rows in student table reference it.
that same pattern can repeated 1 to-to-many relationship. example, if student can related at most 1 section can add foreign key in same way.
if there's many-to-many relationship, introduce relationship table has foreign keys referencing 2 related entity tables.
if student can related zero, 1 or more section, , section can related zero, 1 or more student, that's example of many-to-many relationship.
we can introduce new table (as example):
create table student_section ( student_id int not null comment 'pk, fk ref student' , section_id int not null comment 'pk, fk ref section' , primary key (student_id, section_id) , constraint fk_student_section_student foreign key student_id references student(s_id) on delete cascade on update cascade , constraint fk_student_section_section foreign key section_id references section(sec_id) on delete cascade on update cascade ) with in place, establish relationship between student , section, insert row new student_section table. if student related section, add row table, referencing same student, different section.
the value stored in student_id column refers row in student table; , value stored in section_id column refers row in section table.
(the many-to-many relationship composed of rows in new table has one-to-many relationship 2 other tables.)
Comments
Post a Comment