Working in mysql with foreign keys -
i want create mysql database foreign keys. when insert test data notice when in tables tblcontact , tbladdress foreign key null. know basic question can give suggestions?
create table tblcustomers ( customerid int not null auto_increment primary key, firstname varchar(30) not null, lastname varchar(30) not null, vat varchar(30) not null, customervisible varchar(1) not null default 't' ); create table tblcontact ( contactid int not null auto_increment primary key, email varchar(100), phone varchar(100), customerid int, constraint fk_customerid foreign key (customerid) references tblcustomers(customerid) ); create table tbladdress ( addressid int not null auto_increment primary key, street varchar(100), housenumber varchar(15), city varchar (100), country varchar (100), customerid int, constraint fk_customerida foreign key (customerid) references tblcustomers(customerid) ); insert tblcustomers (firstname, lastname,vat) values ("john","doe","uv45856855"); insert tblcontact (email, phone) values ("0000001","johndoe@gmail.com"); insert tbladdress (street,housenumber,city,country) values ("berkenlaan","1a","harelbeke","belgie");
you misunderstood concept of foreign keys.. foreign key key used link 2 tables together.. in order relate particular row parent row should enter reference (primary key of parent) in child.
its not automatic.. have enter customerid
of tblcustomer
in tbladdress
, tblcontact
manually contain dependency.
you didnt in code.. thats why getting null. how mysql know data putting in tbladdress
, tblcontact
related specific customer?
if want happen automatically can create trigger using last_insert_id()
.
example:-
create trigger tbladdress_auto_insert after insert on `tbladdress` each row begin insert tbladdress (customerid) values (last_insert_id()); end;
similarly tblcontact
.
hth
Comments
Post a Comment