sql-server - 外键到复合键

标签 sql-server foreign-keys

我有一个问题,我需要将单个外键引用到另一个表中的复合键。

我的数据库结构如下:

CREATE TABLE available_trip (
trip_code integer not null,
date datetime not null,
primary key(trip_code, date),
FOREIGN KEY (trip_code) REFERENCES trip (trip_code)
);

CREATE TABLE booking (
    available_trip_code integer not null,
    customer_code integer not null,
    date datetime not null,
    deposit float not null,
    total_price float not null,
    has_paid float not null,
    description_en nvarchar(12) null,
    finance_type_code nvarchar(12) not null,
    primary key(available_trip_code, customer_code, date),
    FOREIGN KEY (available_trip_code) REFERENCES available_trip (trip_code, date),


FOREIGN KEY (customer_code) REFERENCES customer (customer_code),
            FOREIGN KEY (finance_type_code) REFERENCES finance_type (finance_type_code)
        );

我的问题是:如何让 booking.available_trip_code 引用 available_trip.trip_codeavailable_trip.date

最佳答案

如果您引用复合主键,您的外键还需要包含所有这些列 - 因此您需要类似的内容:

FOREIGN KEY (available_trip_code, date) 
            REFERENCES available_trip (trip_code, date)

如果您的表格中尚未包含所有这些列,则需要添加它们。

关于sql-server - 外键到复合键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8575046/

相关文章:

sql - 内连接三个表

MySQL 错误 150

MySQL:如果存在外键则插入

sql - 检查外键约束 "online"

sql-server - SQL Server FTI : How to check table status?

SQL Server UPDATE 与左连接?

python - 仅当另一个模型字段为真时才需要管理站点中的模型字段

mysql - SQL 无法添加外键?

sql - 使用 MSSQL 查询获取父级的所有子级

sql-server - 如何在批处理文件中获取SQL Server脚本错误