Not able to create foreign key "There are no primary or candidate keys in the referenced table" - sql

This is my table 1:
CREATE TABLE PurchasedProducts
(
Purchase_Order_No int,
Purchase_Product_ID int FOREIGN KEY REFERENCES Inventory(In_Product_ID),
Purchase_Quantity int NOT NULL,
Purchase_Status varchar(7) NOT NULL,
PRIMARY KEY(Purchase_Order_No, Purchase_Product_ID)
);
This my table 2:
CREATE TABLE PurchasedDate
(
PD_PO_No int NOT NULL PRIMARY KEY FOREIGN KEY REFERENCES PurchasedProducts(Purchase_Order_No),
PD_Date date NOT NULL
);
I executed the first table successfully, but when I execute the second table It is showing this error message:
There are no primary or candidate keys in the referenced table 'PurchasedProducts' that match the referencing column list in the foreign key 'FK__Purchased__PD_PO__0B5CAFEA'.
I don't what is the problem is. Please help me!

The primary key in your PurchasedProducts table is made up of two columns:
PRIMARY KEY(Purchase_Order_No, Purchase_Product_ID)
So any child table that wants to reference that also must have these exact two columns:
CREATE TABLE PurchasedDate
(
PD_PO_No int NOT NULL PRIMARY KEY,
Purchase_Product_ID INT NOT NULL,
PD_Date date NOT NULL
);
ALTER TABLE dbo.PurchasedDate
ADD CONSTRAINT FK_PurchaseDate_PurchasedProducts
FOREIGN KEY(PD_PO_No, Purchase_Product_ID)
REFERENCES PurchasedProducts(Purchase_Order_No, Purchase_Product_ID)
A foreign key can only reference the whole primary key of a parent table - you cannot reference only one column out of 2 from the parent table's PK.

Related

SQL table stopping me from adding foreign key

I'm creating a SQL table in VS that stores what rooms each client is, So the table has RoomId (int) and UserID (int).
Because I only want to add to the table only rooms and clients that exist they are both keys that have a foreign key to 2 tables, one that stores RoomID and Name and another that stores Client ID and Name.
Room and UserId tables:
CREATE TABLE [dbo].[UsersInRoomsTable]
(
RoomId INT NOT NULL,
UserId INT NOT NULL,
CONSTRAINT PK_RS PRIMARY KEY(RoomId, UserId),
CONSTRAINT [fk_room] FOREIGN KEY([RoomId]) REFERENCES [dbo].[RoomsTable]([RoomId]),
CONSTRAINT [fk_user] FOREIGN KEY ([UserId]) REFERENCES [dbo].[UserInfoTable] ([UserId])
);
Table that stores all the users:
CREATE TABLE [dbo].[UserInfoTable]
(
[UserName] NVARCHAR (50) NOT NULL,
[UserId] INT NOT NULL,
CONSTRAINT [PK_roomuser] PRIMARY KEY CLUSTERED ([UserName] ASC, [UserId] ASC)
);
Table that stores all the rooms
CREATE TABLE [dbo].[RoomsTable]
(
[RoomId] INT NOT NULL,
[RoomName] NVARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([RoomId] ASC)
);
Everything works except the last line in the Rooms and users table:
CONSTRAINT [fk_user] FOREIGN KEY ([UserId]) REFERENCES [dbo].[UserInfoTable] ([UserId])
When I try to Update the table I get an error SQL71516:
SQL71516: The referenced table '[dbo].[UserInfoTable]' contains no primary or candidate keys that match the referencing column list in the foreign key.
If the referenced column is a computed column, it should be persisted
How can I solve this problem and what is causing it?
Edit: I think I know what is code is colliding: For some reason I can not have a foreign key connecting to a key that contains 2 indexes IE: fk_user is a Fk to table UserInfoTable that has 2 keys (UserID and UserName)
is there a way to pass this obstacle?
The columns of a foreign key have to match the columns they reference by number, type and order.
You have a primary key on userinfotable of (username, userid). But in usersinroomstable you are trying to let the foreign key (userid) to reference that. The number of columns doesn't match, so the foreign key cannot be added.
Presumably the username shouldn't really be part of the primary key of userinfotable and got there by accident. Remove it from the primary key constraint.
Or, if username has to be in the primary key, add such a column to the table usersinroomstable and add it to the foreign key constraint.

How to add foreign key that points to one of 2 tables with Postgres?

I want to add a foreign key that is check record_id of activity exists in one of the record or personal_record tables. Is it possible to do with Postgres?
CREATE TABLE record
(
id BIGSERIAL PRIMARY KEY
);
CREATE TABLE personal_record
(
id BIGSERIAL PRIMARY KEY
);
CREATE TABLE activity
(
id BIGSERIAL PRIMARY KEY,
record_id BIGINT NOT NULL,
CONSTRAINT record_fk FOREIGN KEY (record_id) REFERENCES record (id)
);
As stated, this is not possible. One possibility is generated columns and nullable references:
CREATE TABLE activity (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
private_record_id BIGINT,
private_personal_record_id BIGINT,
record_id BIGINT GENERATED ALWAYS AS (COLAESCE(private_record_id, private_personal_record_id)),
CHECK( (private_record_id IS NOT NULL AND private_personal_record_id IS NULL) OR
(private_record_id IS NULL AND private_personal_record_id IS NOT NULL)
),
CONSTRAINT fk_activity_record_id FOREIGN KEY (private_record_id) REFERENCES record(id),
CONSTRAINT fk_activity_record_id FOREIGN KEY (private_personal_record_id) REFERENCES personal_record(id),
);
You might also want to look into inheritance.

Reservation table query

when I execute my reservation table query, I get an error.
Any help?
This is my reservation table query
CREATE TABLE RESERVATION
(
NUMCHAMBRE INT FOREIGN KEY REFERENCES CHAMBRE (NUMCHAMBRE) ,
NUMHOTEL INT FOREIGN KEY REFERENCES HOTEL (NUMHOTEL),
NUMCLIENT INT FOREIGN KEY REFERENCES CLIENT (NUMCLIENT),
DATEARRIVE DATE,
DATEDEPART DATE,
PRIMARY KEY (NUMHOTEL, NUMCLIENT, DATEARRIVE)
);
This is the error I get:
Msg 1776, Level 16, State 0, Line 2
There are no primary or candidate keys in the referenced table 'CHAMBRE' that match the referencing column list in the foreign key 'FK__RESERVATI__NUMCH__2BFE89A6'.
Msg 1750, Level 16, State 0, Line 2
Could not create constraint or index. See previous errors.
According to your comment, the primary key on chambre is composite. So the foreign key reference needs to include all the columns:
CREATE TABLE RESERVATION (
NUMCHAMBRE int,
NUMHOTEL int Foreign Key REFERENCES HOTEL (NUMHOTEL),
NUMCLIENT int Foreign Key REFERENCES CLIENT (NUMCLIENT),
DATEARRIVE date,
DATEDEPART date,
foreign key (numhotel, numchambre) references chambre (numhotel, numchambre);
)
The column NUMCHAMBRE you're referencing in table CHAMBRE must be a primary key column, i.e. you can't just reference any column.
You can declare it as the primary key like this:
alter table CHAMBRE add primary key (NUMCHAMBRE);
Primary key columns need to be not null, so if NUMCHAMBRE is nullable, the above command will fail.
Update:
Based on your comment below, your table definition should be like this, i.e. you need to reference both columns of the primary key:
CREATE TABLE RESERVATION (
NUMCHAMBRE int,
NUMHOTEL int not null Foreign Key REFERENCES HOTEL (NUMHOTEL),
NUMCLIENT int not null Foreign Key REFERENCES CLIENT (NUMCLIENT),
DATEARRIVE date not null,
DATEDEPART date,
PRIMARY KEY (NUMHOTEL,NUMCLIENT,DATEARRIVE),
Foreign Key (NUMCHAMBRE,NUMHOTEL) REFERENCES CHAMBRE (NUMCHAMBRE,NUMHOTEL)
);
Note the additional not null constraints, as these will be necessary in order to create the primary key on this table using SQL Server.

Foreign key in the first table

I have a question about foreign keys.
How does it work when I want to add a foreign key to the first table that I make that references to the primary key of the second table I create?
CREATE TABLE table1
(
name_id INT NOT NULL,
team TEXT REFERENCES table2(team_id),
PRIMARY KEY(name_id)
);
CREATE TABLE table2
(
team_id INT NOT NULL,
teamname TEXT,
PRIMARY KEY(team_id)
);
If I try the code above I get the following error:
ERROR: relation "" does not exist
Thanks in advance.
Either create the second table first. Or use alter table. That is, create the first table without the reference and then do:
alter table table1 add constraint fk_table1_team
foreign key (team_id) REFERENCES table2(team_id);
The declaration for table1 would be:
CREATE TABLE table1 (
name_id INT NOT NULL,
team_id INT,
PRIMARY KEY(name_id)
);
The reference between the tables should be on the primary key and certainly not on a character column, if an integer is available.
here's the syntax of creating a table with Foreign key:
CREATE TABLE table11
(
name_id INT NOT NULL,
team INT,
PRIMARY KEY(name_id),
foreign key(team) references table22(team_id)
);
CREATE TABLE table22
(
team_id INT NOT NULL,
teamname TEXT,
PRIMARY KEY(team_id)
);
but there was another problem. a foreign key from a child table cannot reference to a primary key from a parent folder if they do not contain the same type. in your code team was of TEXT and team_id was of INT which cannot be.

No matching unique or primary key for this column-list in Oracle

I have created PERSON table in Oracle by this SQL syntax:
Create table person
(
p_id int not null,
personName char(5) not null );
Then I am trying to create ORDERS table with the following syntax:
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)
REFERENCES person(p_id) );
But I am getting the following error .
No matching unique or primary key for this column-list.
What is the problem ? How can I solve this ?
Add primary key to person table:
CREATE TABLE person(
p_id int not null,
personName char(5) not null,
PRIMARY KEY (p_ID)
);
SqlFiddleDemo
Foreign keys enforce a one-to-many relationship. That is, however many records there are in the dependent table they can only reference a single record in the parent table. This means the referenced column(s) in the parent table must be constrained by a PRIMARY or UNIQUE key.
The error message is telling you that there is no such constraint on person(p_id). And lo! if we compare the two DDL statements you have posted we can see that you have created a primary key for ORDERS but not for PERSON.
The solution is simple: constrain P_ID by adding a primary key to PERSON. You can either drop and re-create the table, or you can use an alter table statement to add a primary key.
You should add primary key to person table.
try this:
ALTER TABLE Person
ADD CONSTRAINT p_id PRIMARY KEY (p_id);