گذری بر مفاهیم relationship
نویسنده: محمد سلیم آبادی
تاریخ: ۱۳۹۱/۱۱/۰۶ ۲۲:۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
syntax مربوط به قید کلید خارجی در مدل ستونی به صورت زیر است:
<column_constraint> ::=
[ CONSTRAINT constraint_name ]
{ ...
| [ FOREIGN KEY ]
REFERENCES [ schema_name . ] referenced_table_name [ ( ref_column ) ]
[ ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ]
[ ON UPDATE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ]
[ NOT FOR REPLICATION ]
...
}
create table parent ( col1 int not null, col2 int not null, col3 char(1) null, -- Composite Primary Key primary key(col1, col2) );
و جدول child که دارای قید کلید خارجی ترکیبی به نام fk_comp است و به جدول parent ارجاع داده است:
create table child ( col0 int primary key, col1 int null, col2 int null, -- Composite Foreing Key Constraint constraint fk_comp foreign key (col1, col2) references parent(col1, col2) );
در این DDL هم از قید جدولی برای تعریف کلید خارجی ترکیبی استفاده شده است.
نمودار این دو جدول:
پس به عنوان نتیجه گیری، هرگاه جدول اصلی دارای کلید ترکیبی بود در جداول child نیز باید از کلید خارجی ترکیبی برای ایجاد relationship استفاده نمود.
اما این دو جدول را به یک شیوه دیگر نیز میتوان طراحی نمود. در جدول parent ترکیب دو ستون col1 و col2 را منحصربفرد (unique) گرفته و ستونی دیگر (مثلا از نوع identity) را به عنوان کلید اولیه در نظر گرفت (یا یک ستون از نوع محاسباتی تعریف کرده و آن را کلید قرار داد)
create table parent ( col0 int not null primary key identity, col1 int not null, col2 int not null, col3 char(1) null, -- Composite Unique Key unique(col1, col2) ); create table child ( col0 int primary key, col1 int null references parent );
create table chart ( chart_nbr int not null primary key, parent_nbr int null references chart, chart_name varchar(5) null );
create table letters ( letter_nbr int primary key, sec_sender int not null references chart, sec_reciver int not null references chart );
create table pilot ( pilot_code int primary key, pilot_name varchar(20) ); create table paths ( path_code int primary key, path_name varchar(20) ); create table junction ( pilot_code int references pilot, path_code int references paths, primary key (pilot_code, path_code) );
create table student ( std_code int primary key, std_name varchar(25) not null ); create table football ( std_code int primary key constraint one_to_one_fk references student, std_cnt_goal int not null default (0) );
/* A
/ \
B C
| /|\
D E F G
|
H
*/
declare @t table
(
id char(1) primary key not null,
pid char(1) null --references @t
);
insert @t
values ('A', null), ('B','A'),('C','A'),
('D','B'), ('H','D'),('E','C'),('F','C'),('G','C');
with cte as
(
select id
from @t
where pid = 'A'
union all
select t.id
from cte c
join @t t
on t.pid = c.id
)
select * from cte
create nonclustered index ix_parent on table_name (parent_id)