Click here to Skip to main content
15,911,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have 3 tables as:

/*contains user id and name*/
SQL
create table kprofile
( kid bigint unsigned,
  name varchar(30) not null,
  constraint pkkprofile primary key(kid)
);


/*contains code and name of services*/
SQL
create table scode
(
  code smallint  unsigned,
  name varchar(50) not null,
  constraint pkscode primary key (code)
);


/*contains id of the user and code of services provided by him*/
SQL
create table kserviceprovide
(
  kid bigint unsigned,
  scode smallint unsigned not null,
  constraint kserviceprovide primary key(kid,scode),
  constraint fkkserviceprovideonkid foreign key(kid) references kprofile(kid),
  constraint fkkserviceprovideonscode foreign key(scode) references scode(code)
);



In the table kserviceprovide,I am aware of concept that foreign key will not work at this time since it is also used as composite primary key.

But, somehow I need to implement such behaviour. I need to check for the presence of kid and scode in upper 2 tables before inserting any row in 3rd table.

How can I implement this behaviour?
Posted
Comments
Tomas Takac 11-Jan-16 2:59am    
What do you mean by "foreign key will not work"? What will not work?
Member 11040029 11-Jan-16 3:08am    
foreign key doesnt work, it allows insertion for a record.
For e.g.:
insert into kserviceprovide values (9870653421,110);

let us consider provided kid-9870653421 is not present in kprofile table and scode-110 is also not present in code table.
If I have applied foreign key, then mysql must not insert these values but these values are inserted with no errors.
Tomas Takac 11-Jan-16 3:12am    
I'm sorry but you must be doing something wrong. I just tested in SQL Fiddle[^] and got this error: Cannot add or update a child row: a foreign key constraint fails (`db_9_5b735`.`kserviceprovide`, CONSTRAINT `fkkserviceprovideonkid` FOREIGN KEY (`kid`) REFERENCES `kprofile` (`kid`))
Member 11040029 11-Jan-16 3:13am    
I mentioned the question for MYSQL
Tomas Takac 11-Jan-16 3:19am    
Ok, so you don't know SQL Fiddle. Check it out, you will certainly love it. Unfortunately it only provides links for successful queries not on errors. I tested with MySQL 5.6 - FKs definitely work.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900