【问题标题】:How do i create a foreign key in sql server with multiple columns?如何在具有多列的 sql server 中创建外键?
【发布时间】:2021-11-23 06:59:06
【问题描述】:

我正在尝试创建外键:

create table visit
      (Num_vst int primary key,
      date_vst date,
      num_agnt int,
      code_type int,
      Constraint fk_vst foreign key (num_agnt,code_type) 
        references agente,type_de_verification  (num_agnt,code_type);

问题出在哪里?

【问题讨论】:

  • 您似乎在相关表的名称中有错字:agente,type_de_verification。这应该是一个表名。也许那个逗号应该是一个点。
  • @TheImpaler 有 2 张桌子!比如 numa_agnt 与 agente 相关,而 code_type 与 type_de_verification 相关!与 2 个表相关的外键!我错了吗?
  • 外键只能引用一张表,而且必须是完整的键。

标签: sql sql-server key


【解决方案1】:

您正在描述两个表的两个独立关系:

num_agnt 与 agente 相关,code_type 与 type_de_verification 相关

在这种情况下,您可以定义两个外键,如下所示:

create table visit (
  Num_vst int primary key,
  date_vst date,
  num_agnt int,
  code_type int,
  constraint fk1 foreign key (num_agnt) references agente (num_agnt),
  constraint fk2 foreign key (code_type)
    references type_de_verification (code_type)
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 2020-04-05
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多