Click here to Skip to main content
15,904,415 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to make relationship and query in my sql?????
Posted
Comments
ZeeroC00l 7-Apr-11 2:54am    
Can you be more specific ?? Did you mean, how to create a relation between two tables ?
zeroseven08 7-Apr-11 2:57am    
yes,,,i want to create a relation between two table and
at the same time want to determine the type of relation,
whether one to one, one to many or many to many..
please help me,,senior
zeroseven08 7-Apr-11 3:46am    
thx u brother for ur solution,,
oya..
i want to create store procedure in my sql..
but i don't know how to create it?
can u help me senior..
ZeeroC00l 7-Apr-11 4:37am    
With pleasure. But can you please post it as a new question so that others browsing the site looking for the same detail can find it easily.

 
Share this answer
 
For creating a relation between the tables you can make use of PRIMARY KEY and FOREIGN KEY.
Depeding on which engine is being run you you might have to make a very minute adjustment to your query.

SQL
CREATE TABLE temp1(
       slNumber INT(4) NOT NULL AUTO_INCREMENT,
       .....
       PRIMARY KEY(slNumber)
)


SQL
CREATE TABLE temp2(
       slNumber INT(4) NOT NULL AUTO_INCREMENT,
       idNumber INT(4) NOT NULL AUTO_INCREMENT,
       .....
       PRIMARY KEY(idNumber),
       FOREIGN KEY(slNumber) REFERENCES temp1(slNumber)
)ENGINE=INNODB


Specifying the
ENGINE=INNODB
is necessary as MYISAM engine does not support the FOREIGN KEY.

For getting the relationship details like One-One, One-Many or Many-Many, i would suggest you make use of MySql Workbench[^] As it provides you with a GUI that can be used to get the details of relationship.


There are few more things that you need to be careful about before you make use of the FOREIGN KEY.
Its always advisable to make use of
ON DELETE CASCADE 
and
ON UPDATE CASCADE
after the table with the FOREIGN KEY is created.
And make sure that the size of the FOREIGN KEY matches the size of the PRIMATY KEY.


BR//
Harsha Narayana
 
Share this answer
 
v2

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