作为一般规则,您希望创建一个单独的表来显示关系。
第 1 期(Friendster)
create table user_tab
(user_id varchar2(10) not null,
user_name varchar2(20),
constraint u_pk primary key (user_id)
);
create table friend
(user_id varchar2(10) not null,
user_id_friend varchar2(10) not null,
constraint u_f_pk primary key (user_id, user_id_friend),
constraint friend_uid_fk_user_tab foreign key (user_id)
references user_tab(user_id),
constraint friend_uidf_fk_user_tab foreign key (user_id_friend)
references user_tab(user_id)
);
insert into user_tab(user_id) values ('u1');
insert into user_tab(user_id) values ('u2');
insert into user_tab(user_id) values ('u3');
insert into friend(user_id, user_id_friend)
values ('u1','u2');
insert into friend(user_id, user_id_friend)
values('u1','u3');
insert into friend(user_id, user_id_friend)
values('u2','u1');
insert into friend(user_id, user_id_friend)
values('u2','u3');
表友是 user_tab 中两个条目之间的关系表。
对于问题 2 (flickr)
create table pic_table
(pic_id number not null,
user_id_uploader varchar2(10) not null,
pic_snap bfile,
constraint snp_pk primary key (pic_id),
constraint pic_table_uidu_fk_user_tab foreign key (user_id_uploader)
references user_tab(user_id)
);
create table pic_rating (
pic_id number not null,
user_id_rater varchar2(10) not null,
rating number,
constraint pic_rating_pk primary key(pic_id,user_id_rater),
constraint pic_rating_pid_fk_pic_table foreign key (pic_id)
references pic_table(pic_id),
constraint pic_rating_uidr_fk_user_tab foreign key (user_id_rater)
references user_tab(user_id)
);
insert into pic_table(pic_id, user_id_uploader) values
(1, 'u1');
insert into pic_rating(pic_id, user_id_rater, rating) values
(1, 'u2', 2);
insert into pic_rating(pic_id, user_id_rater, rating) values
(1, 'u3', 3);
表 pic_rating 是 pic_table 和 user_tab 之间的关系表。
尝试制定一些添加、更新和删除关系的用例场景,你会明白为什么这是标准的数据库设计实践。