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

I am currently making a database back end system on an airport, using sql through the phpmyadmin server. 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. 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.
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?

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

Related

Why is my create table failing? - does not match primary key

This is what I am trying to create:
CREATE TABLE VEHICLEREPORT
(
DeptID char(2) not null,
Vin# char(3) not null,
Miles varchar(6) not null,
Bill# char(3) not null,
EID char(3) not null,
PRIMARY KEY (DeptID, Vin#),
FOREIGN KEY (bill#) REFERENCES billing,
FOREIGN KEY (EID) REFERENCES Employee
);
The issue is with my reference to billing. The error says:
The number of columns in the referencing column list for foreign key 'FK__VEHICLERE__Bill#__5AEE82B9' does not match those of the primary key in the referenced table 'Billing'.
but my billing table entered fine:
CREATE TABLE BILLING
(
VIN# char(3),
BILL# char(3),
PRIMARY KEY (VIN#, Bill#),
FOREIGN KEY (VIN#) REFERENCES vehicle
);
What am i missing with this?
Appreciate the help.
If you think of the foreign key as establishing a parent-child relationship between two tables, then the parent side column(s) need to be unique.
From Wikipedia:
In the context of relational databases, a foreign key is a field (or collection of fields) in one table that uniquely identifies a row of another table or the same table. ... In simpler words, the foreign key is defined in a second table, but it refers to the primary key or a unique key in the first table.
In your example, there is no guarantee that VIN# is unique in VEHICLEREPORT. Below are your options
VIN# is guaranteed to be unique in VEHICLEREPORT. In this case add a UNIQUE constraint on VIN# on the VEHICLEREPORT table. The error will go away.
VIN# is not unique in VEHICLEREPORT (doesn't seem likely). If this is the case, then likely there is a flaw in the design of your BILLING table as it could likely point to more than one row in VEHICLEREPORT. You should consider adding DeptID column to BILLING and creating a composite foreign key.
Also if VIN# is unique (case 1 above), you should think of why DeptID is present in the PK. Maybe the right fix at the end is to drop DeptID from the primary key.

Create a table in SQL where the Composite Primary Key is also a Foreign Key

I need to create a table called LFM_Enroll in SQL that has a composite primary key of Student_ID and Section_Number. Student_ID is also a foreign key, it references Student_ID in the LFM_Student table and Section_Number is also a foreign key, it references Section_Number in the LFM_Section table. How do I write the constraints and foreign keys? I've attached an image of the tables and below is what I have done so far. After the LFM_Enroll table is created I need to update one row. I tried doing so but kept getting the below error.
: Error starting at line : 173 in command -
UPDATE LFM_Enroll
SET Student_ID = 1234567,
Section_Number = 01234
WHERE Student_ID = 900000 AND Section_Number = 4138
Error report -
ORA-02291: integrity constraint (SYSTEM.FK_LFM_ENROLL_SECTION_NUMBER) violated - parent key not found.
Tables Thanks in advance for all your help.
CREATE TABLE LFM_Enroll (
Student_ID char(7),
Section_Number char(4),
constraint PK_LFM_Enroll Primary Key (Student_ID,Section_Number),
constraint FK_LFM_Enroll_Student_ID
Foreign Key (Student_ID,Section_Number) references LFM_Student (Student_ID),
constraint FK_LFM_Enroll_Section_Number
Foreign Key (Student_ID,Section_Number) references LFM_Section (Section_Number)
);
Your foreign key constraints are not right. You are trying to map two columns {Student_ID,Section_Number} to a single column LFM_Student.Student_ID.
The number of columns in the principal key must match the number of columns in the foreign key. In other words, the key LFM_Student is one column (Student_ID), so the foreign key also needs to be a single matching column - in this case LFM_Enroll.Student_ID. Correct DDL would be:
constraint FK_LFM_Enroll_Student_ID
Foreign Key (Student_ID) references LFM_Student (Student_ID),
constraint FK_LFM_Enroll_Section_Number
Foreign Key (Section_Number) references LFM_Section (Section_Number)
I'm not quite sure why your RDBMS is allowing what you have, but it may be using the first column and simply ignoring the second. In which case FK_LFM_Enroll_Section_Number is creating a foreign key LFM_Enroll.Student_ID => LFM_Section.Section_Number.
The error indicates that the values with which you are trying to update the two columns may not exist in Student and / or Sections tables i.e. 1234567 doesn't exists in the student table and / or 01234 doesn't exist in your section table . You should try inserting new rows or updating existing ones with the new values you are trying to update your foreign keys with.
[Edit: For defining constraints refer lc.'s post]

SQL: Primary and foreign key

I am creating a table that has two values that are both primary and foreign at the same time. I do not know how to create them in SQL. Here is what I did but I get the error, there must only be one primary key. what is the correct way?
CREATE TABLE movie_director(
director_id CHAR(8)
constraint pk_director_id_movie_director
PRIMARY KEY
constraint fk_director_id_movie_director
REFERENCES director,
movie_id VARCHAR(30)
constraint pk_movie_id_movie_director
PRIMARY KEY
constraint fk_movie_id_movie_director
REFERENCES movie
)
What you seem to be looking for is a compound primary key. Change your table definition to something like the following:
CREATE TABLE movie_director(
director_id CHAR(8)
constraint fk_director_id_movie_director
REFERENCES director,
movie_id VARCHAR(30)
constraint fk_movie_id_movie_director
REFERENCES movie,
CONSTRAINT PK_MOVIE_DIRECTOR
PRIMARY KEY (DIRECTOR_ID, MOVIE_ID));
Your error seems pretty clear. There can only be one PRIMARY KEY on a table.
You need to create a COMPOUND PRIMARY KEY which consists of two columns (director_id,movie_id).
From wikipedia:
In database design, a compound key is a key that consists of two or more attributes that uniquely identify an entity occurrence.

How to use two columns in a foreign key constraint

I have two tables:
Article
Subscription
In the Article table I have two columns that make up the primary key: id, sl. In the Subscription table I have a foreign key 'idsl`.
I use this constraint :
constraint FK_idsl
foreign key (idsl) references CSS_SubscriptionGroup(id, sl)
But when I run the query, I getting this error:
Number of referencing columns in foreign key differs from number of referenced columns, table X
In Article Table I have two fields that are the primary key: id,sl. In the Subscription Table I have a foreign key 'idsl`
This design is broken - it is apparent that the composite primary key in Article(id, sl) has been mangled into a single compound foreign key in table Subscription. This isn't a good idea.
Instead, you will need to change the design of table Subscription to include separate columns for both id and sl, of the same type as the Article Table, and then create a composite foreign key consisting of both columns, referencing Article in the same order as the primary key, e.g:
CREATE TABLE Article
(
id INT NOT NULL,
sl VARCHAR(50) NOT NULL,
-- Other Columns
CONSTRAINT PK_Article PRIMARY KEY(id, sl) -- composite primary key
);
CREATE TABLE Subscription
(
-- Other columns
id INT NOT NULL, -- Same type as Article.id
sl VARCHAR(50) NOT NULL, -- Same type as Article.sl
CONSTRAINT FK_Subscription_Article FOREIGN KEY(id, sl)
REFERENCES Article(id, sl) -- Same order as Article PK
);
Edit
One thing to consider here is that by convention a column named table.id or table.tableid should be unique, and is the primary key for the table. However, since table Article requires an additional column sl in the primary key, it implies that id isn't unique.
correct syntax for relation:
CONSTRAINT FK_OtherTable_ParentTable
FOREIGN KEY(OrderId, CompanyId) REFERENCES dbo.ParentTable(OrderId, CompanyId)
You must try like this:
constraint FK_idsl foreign key (id,sl) references CSS_SubscriptionGroup(id,sl)

Will not specifying a foreign key constraint get me in trouble?

I have the following T-SQL in VS2013:
CREATE TABLE [dbo].[Jugo]
(
[JugoID] INT IDENTITY (1, 1) NOT NULL,
[Jugo] NVARCHAR (50) NOT NULL,
[ColorID] INT NOT NULL,
[IngreID] INT NOT NULL,
PRIMARY KEY CLUSTERED ([JugoID] ASC),
FOREIGN KEY (ColorID) REFERENCES Color (ColorID)
ON UPDATE CASCADE ON DELETE CASCADE,
FOREIGN KEY (IngreID) REFERENCES Ingrediente (IngreID)
ON UPDATE CASCADE ON DELETE CASCADE
);
And I get the following message before updating the database:
Highlights
None
User actions
Create
Foreign Key: unnamed constraint on [dbo].[Jugo] (Foreign Key)
Foreign Key: unnamed constraint on [dbo].[Jugo] (Foreign Key)
Supporting actions
None
Can I proceed with these unnamed constraints? What would I need the constraints for?
For reference this is what I'm trying to do:
3 tables:
Jugo, Color, Ingrediente: so to create a jugo (juice) you specify name, color and ingredients, color and ingredients are on their own tables, hence the foreign keys I want to define.
Thanks.
As long as the ColorID and IngreID are both primary key in their own tables, you won't have any trouble.
But here's the catch, you didn't constrain your primary keys. It is a good practice to use constraint for every PRIMARY KEY you are using, in that way, when you foreign key it to another table. It can read that it is from another table. I don't know about SQL in VS2013 But here's my sample for SQL Server:
CREATE TABLE JUGO
(
JUGOID numeric identity (1,1) //For auto increment
CONSTRAINT PK_JUGOID PRIMARY KEY (JUGOID),
JUGO nvarchar(50) not null,
.
.
.
)
The PK_JUGOID in CONSTRAINT PK_JUGOID PRIMARY KEY (JUGOID), is user-defined, but it is a good practice to just copy the format of the primary key so you won't be confused when using foreign keys. :)
Foreign keys are for data consistency. You create the foreign keys on columns, so as not to allow invalid entries.
FOREIGN KEY (ColorID) REFERENCES Color (ColorID)
ON UPDATE CASCADE ON DELETE CASCADE,
This constraint makes sure that your jugo can only have a color that exists in the color table. Moreover you have two cascade commands:
ON UPDATE CASCADE means that if color red is ID 5, but you want to change it to 500, the change will be performed automatically for all jugo records. However, an ID should never change, so this is a clause seldom used.
ON DELETE CASCADE means that if you delete red, then you delete all red jugo records with it. I don't know if this is an appropriate case for you. It is used for instance on a users table. Remove a user, so you remove its complete data. But remove a color?
At last you should give your constraints names, so it's easier for you to deal with them.
CONSTRAINT pk_jugo PRIMARY KEY CLUSTERED ([JugoID] ASC),
CONSTRAINT fk_jugo_color FOREIGN KEY (ColorID) REFERENCES Color (ColorID),
CONSTRAINT fk_jugo_ingre FOREIGN KEY (IngreID) REFERENCES Ingrediente (IngreID)