Sql server 2008 SQL Server中主键和外键的规则

Sql server 2008 SQL Server中主键和外键的规则,sql-server-2008,Sql Server 2008,我有以下表格和专栏 汽车 轮胎 主键为CarId和TireId 现在,我想添加一条规则,检查轮胎中的外键CarId是否与汽车中的MarketId相同。我必须添加触发器吗?或者可以采用不同的方式吗?您可以创建一个汽车/轮胎交叉参考表,并将市场信息放在该表上,而不是放在汽车和轮胎表上。然后,任何给定的汽车/轮胎组合自动具有相同的市场ID 当然,这只是一个有用的想法,如果你能够改变那么多的表结构。由于CarID在CAR表中是唯一的,CarID/MarketID组合也将是唯一的。因此,您可以在这两列上创

我有以下表格和专栏

汽车

轮胎

主键为
CarId
TireId


现在,我想添加一条规则,检查
轮胎中的外键
CarId
是否与
汽车中的
MarketId
相同。我必须添加触发器吗?或者可以采用不同的方式吗?

您可以创建一个汽车/轮胎交叉参考表,并将市场信息放在该表上,而不是放在汽车和轮胎表上。然后,任何给定的汽车/轮胎组合自动具有相同的市场ID


当然,这只是一个有用的想法,如果你能够改变那么多的表结构。

由于CarID在
CAR
表中是唯一的,CarID/MarketID组合也将是唯一的。因此,您可以在这两列上创建唯一的索引,这两列可能是外键约束的目标

create table car 
(
  carid       integer not null primary key,
  marketid    integer not null,
  description varchar(100) not null
);

create unique index idx_car_market on car (carid, marketid);

create table tire
(
  tireid       integer not null primary key,
  carid        integer not null references car, -- this fk is not strictly necessary
  marketid     integer not null,
  description  varchar(100) not null  
);

alter table tire
   add constraint fk_tire_car 
   foreign key (carid, marketid)
   references car (carid, marketid);
外键将确保轮胎表中仅使用有效的CarID/MARKID组合

TireId CarId MarketId Description
create table car 
(
  carid       integer not null primary key,
  marketid    integer not null,
  description varchar(100) not null
);

create unique index idx_car_market on car (carid, marketid);

create table tire
(
  tireid       integer not null primary key,
  carid        integer not null references car, -- this fk is not strictly necessary
  marketid     integer not null,
  description  varchar(100) not null  
);

alter table tire
   add constraint fk_tire_car 
   foreign key (carid, marketid)
   references car (carid, marketid);