I am creating a database for tracking the Cricketers and their types. By types I mean Batsman, Bowler, Wicket Keeper, etc.
The issue is a Cricketer might belong to different type. For Example Kapil Dev is both a Batsman and a Bowler.
Inorder to solve this I should create a third table referred to as Junction Table apart from Cricketer and Type tables which is having reference to both Crickter and Type tables and a Composite Key. Here I name it Cricketer Type.
Create database Cricket
use Cricket
Create table Cricketer (CricketerId int identity(1,1) primary key,Cricketer varchar(40))
Create table Type (TypeId int identity(1,1) primary key,Type varchar(40))
insert into Cricketer values ('Sumesh')
insert into Cricketer values ('Nithin')
insert into Cricketer values ('Shalvin')
insert into Cricketer values ('Mongia')
insert into Type values ('Batsman')
insert into Type values ('Bowler')
insert into Type values ('Wicket Keeper')
create table CricketerType(primary key (CricketerId, TypeId),CricketerId int references Cricketer(CricketerId),TypeId int references Type(TypeId) )
insert into CricketerType values (1, 1)
insert into CricketerType values (1, 3)
insert into CricketerType values (2, 2)
insert into CricketerType values (3, 3)
insert into CricketerType values (4, 3)
select * from Cricketer
select * from Type
select * from CricketerType
select C.CricketerId, C.Cricketer, T.Type from Cricketer C, Type T,CricketerType CT where CT.CricketerId = C.CricketerId and Ct.TypeId = T.TypeId
Wednesday, December 2, 2009
Many To Many Relationship Table Script
Labels:
Many To Many,
Many To Many Table Script,
Shalvin,
Sql,
Sql Script
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment