如何将table1中的合成PRIMARY KEY引用到表2作为SQL中的外键?

时间:2015-10-31 11:45:43

标签: sql sql-server

我在创建指向其他表中的复合主键的外键时遇到问题。

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
)

我在stackoverflow中尝试了解决方案,但没有解决问题

alter table flightroute add constraint FK_FlightRoute_CityCountry foreign key FlightRoute(flight_departureCountryCity) references CityCountry (city_code, country_code) 

2 个答案:

答案 0 :(得分:1)

为了创建外键引用的列,应该是PKunique index。由于您已经有PK,因此您可以将列设为unique index

create unique index UI_CityCountry
   on CityCountry(citycountry_id); 

现在创建FK

alter table flightroute
add constraint FK_FlightRoute_CityCountry
foreign key (flight_departureCountryCity)
references CityCountry (citycountry_id) 

答案 1 :(得分:0)

尝试像这样定义你的表:

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
);

即,在第一个表中正确声明主键,然后在第二个表中使用它。

就个人而言,我更喜欢增加数值的主键,但我会保留原始类型。