2014-03-25 2 views
0

데이터베이스의 자식 테이블에서 반복되는 ID를 갖는 것이 장단점입니다.어린이 테이블의 반복 된 ID

예를 들어, 테이블 parent 고려 :

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

을 그리고이 parent 그것을 참조하는 child1 테이블이 있습니다 : 미세하고 좋은, 그리고 아무것도 모든

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 
) 

I는 데 문제는 더 당신이 내려, 더 지루한는 위쪽으로 길을 가입됩니다 : 당신은 드릴 다운 지킬 문제는 온다. 내가 생각 한 하나 개의 솔루션은 모든 자식 테이블에 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가는 것이 중요합니다 귀하의 예제에서 믿고있어.

이렇게하면 어떨까요?

더 정규화 된 두 번째 접근법은 다음과 같습니다. 이것은 parent_child의 id가 증가하는 정수로 가정 할 수 있으므로 항상 자식의 순서를 파악할 수 있다고 가정합니다. @JustKim에 의해

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

솔루션은 OK이지만, PARENT_ID가 null의 경우

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

더욱 갈 수 있습니다, 그 기록은 부모입니다.

물론 한 부모의 자식을 모두 얻으려면 코드에서 재귀를 사용해야합니다.