2014-03-25 54 views
0

我想知道在数据库中的子表中有重复的ID有什么优点和缺点。在儿童表中重复的ID

例如,考虑表parent

create table parent (
    id int, 
    a text, 
    b text 
) 

parentchild1表引用它:

create table child1 (
    id int, 
    parent_id int not null references parent(id), 
    c text, 
    d text 
) 

所有优秀和良好,并没有什么不寻常的。这个问题是在你不停下钻:

create table child2 (
    id int, 
    child1_id int not null references child1(id), 
    e text, 
    f text 
) 

create table child3 (
    id int, 
    child2_id int not null references child2(id), 
    g text, 
    h text 
) 

我有是问题,进一步的你下来,越繁琐就变成向上加入你的方式。一个解决方案,我认为是重复parent ID中的所有儿童表:

create table child2 (
    id int, 
    parent_id int not null references parent(id), 
    child1_id int not null references child1(id), 
    e text, 
    f text 
) 

create table child3 (
    id int, 
    parent_id int not null references parent(id), 
    child2_id int not null references child2(id), 
    g text, 
    h text 
) 

这有助于减少连接的数量,但它也影响数据库的完整性。如果切换child1的父项,则需要始终记住更新所有parent_id列。我的问题是:是否有其他方法来处理这种情况?如果没有,是否有任何方法可以在保留数据完整性的情况下在儿童表中重复一个ID?

回答

1

我从你的例子假设是很重要的关系变为父< -child1 < -child2,而不是父母< -child1和家长< -child2。

那么像这样的东西呢。

create table parent 
(
    id int, 
    a text, 
    b text 
); 

create table child 
(
    id int, 
    parent_id int null references parent(id), 
    previous_child_id int null references child(id) 
    c text, 
    d text 
); 

是比较归一化将是这样的第二种方法。这假定parent_child上的id可以被认为是一个递增的整数,所以你可以总是找出孩子的顺序。

create table parent 
(
    id int PRIMARY KEY, 
    a text, 
    b text 
); 

create table child 
(
    id int PRIMARY KEY, 
    parent_id int null references parent(id), 
    previous_child_id int null references child(id) 
    c text, 
    d text 
); 

create table parent_child 
(
    id serial PRIMARY KEY, 
    parent_id int null references parent(id), 
    child_id int null references child(id) 
); 
0

通过@JustKim解决方案是好的,但如果PARENT_ID为空,你可以走得更远

create table person 
(
    id int, 
    parent_id int null references person(id), 
    c text, 
    d text 
); 

,该记录是父。

当然,要获得一个父母的所有孩子,你必须在你的代码中使用递归。