违反复合键中的 UNIQUE KEY 约束?

Violation of UNIQUE KEY constraint in a composite key?

我是 SQL 的新手,无法理解此错误:违反唯一键约束 'UQ__Flight_L__5DD08D7924EB8625'。无法在对象 'dbo.Flight_Leg' 中插入重复键。重复键值是 (WN380)


Create Table Flight_Leg(
    Leg_number int not null,
    Departure_airport_code varchar(3),
    Scheduled_departure_time varchar(6),
    Arrival_airport_code varchar(3),
    Scheduled_arrival_time varchar(6),

    /*The maximum number of flight legs(Leg_number in the FLIGHT_LEG) cannot exceed 4*/
    CHECK (Leg_number<=4),

    Flight_number varchar(255) not null UNIQUE FOREIGN KEY REFERENCES Flight(Flight_number),
    PRIMARY KEY (Leg_number,Flight_number),
);

INSERT INTO Flight_leg(Flight_number, Leg_number, Departure_airport_code, Scheduled_departure_time, Arrival_airport_code, Scheduled_arrival_time)
VALUES ('G4155', 1, 'SCK', '531PM', 'IWA', '814PM'),
    ('G4154', 1, 'IWA', '406PM', 'SCK', '451PM'),
    ('DL5841', 1, 'OAK', '1240PM', 'LAX', '200PM'),
    ('DL1149',1,'LAX','645PM', 'HNL', '1043PM'),
    ('HA48', 1, 'HNL', '215PM', 'OAK', '930PM'),
    ('AA1522', 1, 'SFO', '1159PM', 'ORD', '604AM'),
    ('AA3472', 1,'ORD', '719AM', 'MSN', '819AM'),
    ('WN380', 1,'MDW', '755AM', 'ONT', '1010AM'),
    ('WN380', 2, 'ONT', '1045AM', 'SMF', '1145AM'),
    ('B6624', 1, 'LAX', '915PM', 'JFK', '522AM');

在我看来,我在 flight_leg 中创建了一个复合键,所以 WN380 具有重复值应该不会产生此错误? 提前致谢!

您对 Flight 有唯一约束,这将不起作用

UNIQUE FOREIGN KEY REFERENCES Flight(Flight_number)

因此,无论您的主索引是什么

,您都不能插入两个相同的 Flight_Legs

制作一个普通的 NON-UNIQUE KEY REFERENCE 它将起作用:

Flight_number varchar(255) not null FOREIGN KEY REFERENCES Flight(Flight_number),

在你的 Flight Table 中,Key 可以是 UNIQE

此致