2

I have 4 tables

A(ida, name)
B(ida, B-specific stuff)
C(ida, C-specific stuff)
D(ida, D-specific stuff)

and i want that another table E could refer to just B OR C (not D). What can i write in the

CREATE TABLE E

?

APC
  • 144,005
  • 19
  • 170
  • 281
As As
  • 2,049
  • 4
  • 17
  • 33
  • What's the significance of `A`? Do `B`, `C` and `D` inherit from it? Does `E` also need to inherit from it and the relationship you described is unrelated to inheritance altogether, or it needs to inherit from `B` or `C` (or even the other way around)? – Branko Dimitrijevic Jun 15 '12 at 12:11

2 Answers2

2

Seems to me that you are trying to use some kind of supertype/subtype -- as opposed to simple vertical partitioning. If so, do introduce a type-discriminator.

Because this is generic example (A, B, C, D ..) it is hard to guess what relates to what, so here are two options as my best guess.


Option 1

enter image description here


Option 2

enter image description here

Damir Sudarevic
  • 21,891
  • 3
  • 47
  • 71
1

You could use a check constraint to enforce that D only references B or C:

create table D
    (
    id int constraint PK_D primary key,
    idb int constraint FK_D_IDB foreign key references B(id),
    idc int constraint FK_D_IDC foreign key references C(id),
    constraint CHK_D_B_OR_C check 
        (
        case when idb is null then 0 else 1 end + 
        case when idc is null then 0 else 1 end = 1
        )
    );

Live example at SQL Fiddle.

Andomar
  • 232,371
  • 49
  • 380
  • 404
  • but i'd like that it refers to B or to C, not to both of them (and i don't think that a null fk in each row is efficient. – As As Jun 15 '12 at 08:52
  • Is it better in your way or with a unique table `A(ida, ..., where)`? I just did 2 month of "lessons of sql/mysql" and we didn-t do very much, so i was thinking to to in this way before asking, and in the site i'm doing i can check that where must be B or C, and then i can check with a trigger if i'm inserting into E a raw with D. – As As Jun 15 '12 at 09:30
  • Triggers are evil, I'd stay away from them. Two foreign keys is usually better than a "type" column, because the type column repeats the information in the foreign keys. – Andomar Jun 15 '12 at 11:05
  • Well, it would be just a check to check (lol) that the type colums isn't D. Why should't i use it? THere wouldn't be other trigger activated after this one. – As As Jun 15 '12 at 11:16