No primary or candidate key in the referenced table - sql

I have created a table Request which has a primary key made up from three columns, and also a foreign key
CREATE TABLE Request
(
Iqama varchar(255) ,
Cid int,
ReqID int,
FOREIGN KEY (Iqama, Cid) REFERENCES Users(Iqama, ID),
PRIMARY KEY (Cid, Iqama, ReqID)
);
I also created the table below which is a multi-valued attribute for table Request, however I am getting an error
Msg 1776, Level 16, State 0, Line 51
There are no primary or candidate keys in the referenced table 'Request' that match the referencing column list in the foreign key 'FK__Request_Services__151B244E'.
Msg 1750, Level 16, State 1, Line 51
Could not create constraint or index. See previous errors.
The table:
CREATE TABLE Request_Services_chosen
(
Iqama varchar(255) ,
Cid int,
ReqId_ int,
Servicechosen varchar(255),
FOREIGN KEY (ReqId_, Iqama, Cid) REFERENCES Request(ReqID, Iqama, Cid),
PRIMARY KEY (ReqId_, Iqama, Cid, Servicechosen)
);
and here is the Users table:
CREATE TABLE Users
(
ID int NOT NULL,
Iqama varchar(255) NOT NULL,
Name varchar(255),
Password varchar(255),
Phone varchar(255),
PRIMARY KEY (Iqama, ID)
);

The primary key in request is defined as (cid, iqama, reqid) but in your REFERENCES clause in request_services_chosen you use (reqid, iqama, cid). That's the wrong order.
Use the same order.
CREATE TABLE Request_Services_chosen(
...
FOREIGN KEY (Cid,Iqama,ReqId_) REFERENCES Request(Cid,Iqama,ReqID),
...
);

Related

SQL queries - There are no primary or candidate > keys in the referenced table

I am trying to create some tables in SQL but when I am running these queries, I am getting the following exception:
Msg 1776, Level 16, State 0, Line 1
There are no primary or candidate keys in the referenced table 'Couple' that match the referencing column list in the foreign key 'FK__wedding__CoupleN__2739D489'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
CREATE TABLE Person
(
FirstName nvarchar (25) NOT NULL,
SurName nvarchar (25) NOT NULL,
id char(9) PRIMARY KEY
CHECK (id LIKE REPLICATE('[0-9]',9)),
PhoneNumber char(10)
CHECK (PhoneNumber LIKE REPLICATE('[0-9]',10)),
Birthday date
CHECK ((GETDATE() - YEAR(Birthday)) > 10)
);
CREATE TABLE Couple
(
Number int identity(1000,1),
Partner1 char(9)
REFERENCES Person(Id) ON DELETE NO ACTION,
Partner2 char(9)
REFERENCES Person(Id) ON DELETE NO ACTION,
CoupleName varchar(25) NOT NULL,
CONSTRAINT PK_Couple1 CHECK (Partner1 <> Partner2),
CONSTRAINT PK_Couple PRIMARY KEY (Partner1, Partner2, Number)
);
CREATE TABLE weddinghall
(
Name varchar (25) PRIMARY KEY,
SeveralSeats int
CHECK (SeveralSeats >= 50 AND SeveralSeats <= 5000),
Kosher char(1)
CHECK (works = 'Y' OR not = 'N'),
PlaceType varchar(25)
CHECK (PlaceType IN s, 'b', 'd', 'doif')),
NumberOfParkingSpaces int
);
CREATE TABLE wedding
(
WeddingHallName varchar (25)
REFERENCES weddinghall(Name) ON DELETE CASCADE,
CoupleNumber int
REFERENCES Couple (Number) ON DELETE CASCADE,
WeddingDate date,
NumberOfGuests Int ,
CONSTRAINT PK_Wedding PRIMARY KEY (CoupleNumber, WeddingHallName)
);
CREATE TABLE WeddingGuests
(
GuestId char(9) references Person (Id) ON DELETE cascade,
CoupleNumber int references Couple (Number) ON DELETE cascade,
WeddingDate date,
WeddingHallName varchar (25) references weddinghall(Name) ON DELETE cascade,
ArrivalConfirmation CHAR(1),
ArrivingToWedding Char(1),
CONSTRAINT PK_WeddingGuests
PRIMARY KEY (GuestId, CoupleNumber, WeddingDate, WeddingHallName)
);
Can you please help?
The error message is telling you that you don't have a unique constraint or primary key on dbo.Couple.Number. That is the third key column in your primary key constraint, and you can't point a foreign key there. You can either:
Add a unique constraint on dbo.Couple.Number
Change the PK to a unique constraint and make dbo.Couple.Number the single-column primary key.

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.

column "parent_id" referenced in foreign key constraint does not exist when creating SQL table

I am new in SQL and trying to understand Foreign key syntax. I know this was asked in multiple questions but each question I found did not seem to teach me what I am doing wrong here.
This is my SQL code:
CREATE TABLE Customer
(
id int primary key,
name varchar(30),
age int,
gender bool
);
CREATE TABLE Minor
(
FOREIGN KEY (parent_id) REFERENCES Customer(id)
);
CREATE TABLE Adult
(
FOREIGN KEY (parent_id) REFERENCES Customer(id)
);
CREATE TABLE Shop
(
id int primary key
);
CREATE TABLE Drink
(
name varchar(30) primary key
);
CREATE TABLE AlcoholicDrink
(
FOREIGN KEY (name) REFERENCES Drink(name)
);
CREATE TABLE NonAlcoholicDrink
(
FOREIGN KEY (name) REFERENCES Drink(name)
);
And this is the error I am getting:
ERROR: column "parent_id" referenced in foreign key constraint does not exist
SQL state: 42703
You need to add fields in your tables to make the reference. Something like this :
CREATE TABLE Customer
(
id int primary key,
name varchar(30),
age int,
gender bool
);
CREATE TABLE Minor
(
minor_id serial primary key,
parent_id int,
other_fields text etc.
FOREIGN KEY (parent_id) REFERENCES Customer(id)
);
This is simply the reason why it's not working.
Like this
CREATE TABLE Customer
(
id int primary key,
name varchar(30),
age int,
gender bool
);
CREATE TABLE Minor
(
parent_id int ,
FOREIGN KEY (parent_id) REFERENCES Customer(id)
);
To add an answer without just a code snippet:
You've got the right idea with FOREIGN KEY (parent_id) REFERENCES Customer(id). This bit adds a constraint or a "rule" to your table. This constraint ensures that parent_id holds a real id in your Customer table.
The error message told us that column "parent_id" referenced in foreign key constraint does not exist. The confusion comes, understandably, from mistaking the constraint declaration for a column declaration.
As others have pointed out, we need to both 10 declare the foreign key constraint and 2) declare the column.
CREATE TABLE Customer
(
id int primary key,
name varchar(30),
age int,
gender bool
);
CREATE TABLE Minor
(
parent_id int, -- Declare the column
FOREIGN KEY (parent_id) REFERENCES Customer(id) -- Declare the constraint
);

I'm trying to alter one of my tables and adding a foreign key it I keep getting the same error

The error I get is:
Msg 1769, Level 16, State 1, Line 30
Foreign key 'fk_pid' references invalid column 'P_ID' in referencing table 'Detainee'.
My table structure:
create table Detainee
(
D_ID bigint primary key identity not null,
Fname nvarchar(50),
Lname nvarchar(50),
Address varchar(200),
DateOfBirth date,
DateOfArrest date,
SourceOfArrest nvarchar(max)
);
create table PrisonCell
(
P_ID bigint primary key not null,
Capacity int,
RemCap int,
C_Type varchar(20)
);
Code to alter table:
alter table Detainee
add constraint fk_pid foreign key(P_ID) references PrisonCell(P_ID)
What you need to do is:
add the column P_ID BIGINT to your table Detainee
then add the FK constraint to that column
Just adding the FK constraint to the table isn't going to automagically add a column as well...
You should be able to do this in a single step:
ALTER TABLE Detainee
ADD P_ID BIGINT
CONSTRAINT fk_pid FOREIGN KEY REFERENCES PrisonCell(P_ID);

Error Create Foreign Key SQL

CREATE TABLE Usuario
(
id int identity not null,
usuario char(20) unique not null,
senha char(10) not null,
tipo_usuario char(15) not null,
primary key (id),
foreign key (tipo_usuario) references TpoUsuario
on update cascade on delete set default
);
CREATE TABLE TpoUsuario
(
id int identity not null,
tipo_usuario char(15) not null,
primary key(id)
);
This use a codes to top, and received this message error.
First I created table TpoUsuario, then I created table Usuario.
Msg 1778, Level 16, State 0, Line 1
Column 'TpoUsuario.id' is not the same data type as referencing column 'Usuario.tipo_usuario' in foreign key 'FK__Usuario__tipo_us__60A75C0F'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
TpoUsuario.id is an int data type column while Usuario.tipo_usuario is char type column
Could you link Usuario.id with TpoUsuario.id or Usuario.usario with TpoUsuario.tipo_usuario
See how to define foreign-keys:
SQL FOREIGN KEY
You say
foreign key (tipo_usuario) references TpoUsuario on update cascade on delete set default
Syntax is FOREIGN KEY (column col1, column col2, ...) REFERENCES table_name(column col1, column col2,...)