[英]How to reference the composited PRIMARY KEY in table1 to table 2 as foreign key in SQL?
I having a problem with creating foreign key that pointing to a composite primary key in other table. 我在创建指向其他表中的复合主键的外键时遇到问题。
CREATE TABLE CityCountry(
city_code VARCHAR(5) NOT NULL,
city VARCHAR(100),
country_code VARCHAR(5) NOT NULL,
country VARCHAR(100),
citycountry_id VARCHAR(105) PRIMARY KEY (city_code, country_code)
)
CREATE TABLE FlightRoute(
flightroute_id INT IDENTITY(1, 1) PRIMARY KEY,
flight_departureCountryCity VARCHAR(105),
flight_id INT FOREIGN KEY
REFERENCES Flight(flight_id)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
flight_departureDateTime DATETIME,
flight_arrivalDateTime DATETIME,
aircraft_code VARCHAR(15) FOREIGN KEY
REFERENCES Aircraft(aircraft_code)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
flight_order SMALLINT
)
I tried the solution in stackoverflow but didnt work out 我在stackoverflow中尝试了解决方案,但没有解决
alter table flightroute add constraint FK_FlightRoute_CityCountry foreign key FlightRoute(flight_departureCountryCity) references CityCountry (city_code, country_code)
In order to create a foreign key referenced columns shoud be PK
or unique index
. 为了创建外键,引用的列应该是PK
或unique index
。 Since you already have a PK
you can make your column a unique index
: 由于您已经拥有PK
,因此可以使您的列成为unique index
:
create unique index UI_CityCountry
on CityCountry(citycountry_id);
Now create FK
: 现在创建FK
:
alter table flightroute
add constraint FK_FlightRoute_CityCountry
foreign key (flight_departureCountryCity)
references CityCountry (citycountry_id)
Try defining your tables like this: 尝试像这样定义表:
CREATE TABLE CityCountry(
citycountry_id VARCHAR(105) NOT NULL PRIMARY KEY,
city_code VARCHAR(5) NOT NULL,
city VARCHAR(100),
country_code VARCHAR(5) NOT NULL,
country VARCHAR(100)
);
CREATE TABLE FlightRoute(
flightroute_id INT IDENTITY(1, 1) PRIMARY KEY,
flight_departureCountryCity VARCHAR(105) FOREIGN KEY
REFERENCES CityCountry(citycountry_id),
flight_id INT FOREIGN KEY
REFERENCES Flight(flight_id)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
flight_departureDateTime DATETIME,
flight_arrivalDateTime DATETIME,
aircraft_code VARCHAR(15) FOREIGN KEY
REFERENCES Aircraft(aircraft_code)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
flight_order SMALLINT
);
That is, declare the primary key correctly in the first table and thenuse it in the second. 也就是说,在第一个表中正确声明主键,然后在第二个表中使用它。
Personally, I prefer primary keys that are incremented numeric values, but I'm leaving your original types. 就个人而言,我更喜欢主键是递增的数值,但是我要保留原始类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.