外键的SQL外键

时间:2013-12-22 19:18:23

标签: sql db2

首先我正在使用DB2。

我的问题:

  • 我有一张带有主键的表A
  • 包含2个主键的表B(其中一个是A的外键)
  • 包含主键的表C
  • 表格D,其主键为BC

如何创建表格D

我的第一个想法是,但它不起作用:

Create Table D(
   A varchar(20) not null references B(A),
   B varchar(20) not null references B(name of prim key attribute from B),
   C varchar(20) not null references C,
   primary key(A,B,C)    
);

希望您了解我的问题,并能帮助我。

2 个答案:

答案 0 :(得分:2)

外键引用列的名称,而不是约束的名称。

设置。 。

create table A (
  col_a int primary key
);

create table B (
  col_a int not null,
  col_b int not null,
  primary key (col_a, col_b),
  foreign key (col_a) references A (col_a)
);

create table C (
  col_c int primary key
);

执行。 。

create table D (
  col_a int not null,
  col_b int not null,
  col_c int not null,
  primary key (col_a, col_b, col_c),
  foreign key (col_a, col_b) references B (col_a, col_b),
  foreign key (col_c) references C (col_c)
);

答案 1 :(得分:0)

正如Marc_s评论的那样,表中只能有一个主键,即表中不能有多个主键。

作为您问题的解决方案,您可以将两列表B和表C组合在一起,它们可以作为表D的主键