简体   繁体   English

是否可以在一个表中引用一个主键作为跨越两个以上表的外键约束?

[英]Is it possible to reference a primary key in one table as a foreign key constraint across more than 2 tables?

I am currently making a database back end system on an airport, using sql through the phpmyadmin server. 我目前正在通过phpmyadmin服务器使用sql在机场上建立数据库后端系统。 The criteria is not meant to be perfect but one of the ideas behind the queries is to imagine that either a customer or flight dispatch officer might be looking at the tables. 该标准并不意味着是完美的,但查询背后的想法之一是想象客户或航班调度员可能正在查看表格。 I was wondering if it was possible to reference a primary key as a foreign key across 2 or more tables. 我想知道是否有可能在两个或更多表中将主键作为外键引用。 In the example below, I want to reference the model number as a foreign key in the bottom 2 tables. 在下面的示例中,我想在底部的2个表中将型号作为外键引用。 I have ensured that the type and character count are the same. 我确保类型和字符数相同。

    CREATE TABLE Aircraft_Model
    (Model_Number varchar (12) NOT NULL,
    seat_capacity int (3),
    CONSTRAINT pk7 primary key (Model_Number));

    CREATE TABLE Licence_type
    (Rank varchar (25) NOT NULL,
    Model_Number varchar (12),
    CONSTRAINT pk9 primary key (Rank));

    CREATE TABLE Aircraft
    (Aircraft_ID varchar (4) NOT NULL, 
    Model_Number varchar(12),
    airport_base text(13),
    CONSTRAINT pk1 PRIMARY KEY (Aircraft_ID));

Is this possible? 这可能吗? I only want the database to be able to perform about 12-15 simple queries. 我只希望数据库能够执行约12-15个简单查询。

Would the syntax of adding a foreign key be something like this? 添加外键的语法会是这样吗?

ALTER TABLE Aircraft
ADD CONSTRAINT fk1 FOREIGN KEY(Model_Number)
REFERENCES Aircraft_Model

Does the same foreign key being referenced from a separate table such as Licence_type need a separate constraint to be added or can it be added from the same one with the same fk1 number? 从单独的表(如Licence_type)中引用的同一外键是否需要添加单独的约束,还是可以从具有相同fk1编号的同一表中添加?

I was wondering if it was possible to reference a primary key as a foreign key across 2 or more tables. 我想知道是否有可能在两个或更多表中将主键作为外键引用。

If you mean, "Can two or more tables have foreign keys that reference the same column?", then, yes, you can do that. 如果您的意思是“两个或多个表是否可以具有引用同一列的外键?”,那么可以。 This seems to be what you mean, but it's not what most people mean when they talk about "a foreign key across 2 or more tables". 这似乎就是您的意思,但这并不是大多数人谈论“跨2个或更多表的外键”时的意思。

Declare two different, separate constraints. 声明两个不同的独立约束。

ALTER TABLE Aircraft
ADD CONSTRAINT fk1 FOREIGN KEY(Model_Number)
REFERENCES Aircraft_Model (Model_Number);

ALTER TABLE License_Type
ADD CONSTRAINT fk2 FOREIGN KEY(Model_Number)
REFERENCES Aircraft_Model (Model_Number);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM