error: there is no unique constraint matching given keys for referenced table "incident" - sql

I know that this question has been already answered a million of times, but I couldn't find any solution. Well I have these three tables on postgres sql.
CREATE TABLE user_account (
id SERIAL not null,
firstName VARCHAR(60) not null,
lastName VARCHAR(60) not null,
password VARCHAR(150) not null,
email VARCHAR(40) not null UNIQUE,
isVolunteer BOOLEAN,
complete BOOLEAN,
CONSTRAINT pk_user PRIMARY KEY (id));
CREATE TABLE incident (
id SERIAL not null,
patientId INTEGER not null,
incidentTime VARCHAR(10) not null,
latitude NUMERIC not null,
longitude NUMERIC not null,
city VARCHAR(60) not null,
state VARCHAR(60),
country VARCHAR(60),
complete BOOLEAN,
CONSTRAINT pk_incident PRIMARY KEY (id, patientId),
CONSTRAINT fk_incident FOREIGN KEY (patientId)
REFERENCES user_account (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE);
CREATE TABLE incident_has_volunteer (
incidentId INTEGER not null,
volunteerId INTEGER not null,
incidentTime VARCHAR(10) not null,
complete BOOLEAN,
CONSTRAINT pk_incident_has_volunteer PRIMARY KEY (incidentId, volunteerId),
CONSTRAINT fk_volunteer FOREIGN KEY (volunteerId)
REFERENCES user_account (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT fk_incident FOREIGN KEY (incidentId)
REFERENCES incident (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE);
When I try to create the table incident_has_volunteer it throws the error there is no unique constraint matching given keys for referenced table "incident".
I tried to add on the third table and the patientId as a foreign key from table incident table but with no luck. I can't understand why it throws this error even if I have already set the primary keys on the incident table.

I'm not an expert in postgres, but I believe that the problem is while fk_incident is referencing incident.id, incident's primary key is made of id + patientId. Since incident.id is guaranteed to be unique only in combination with patientId, there's no way to ensure referential integrity.
I believe that if you add a unique constraint to incident.id (I'm assuming that it would be unique), your foreign key will be legal.

Very simply - one table of primary key acts as a foreign key for another table, so you must ensure that both key is referenced or not.
Simply you will not assign foreign key to the column of another table which does not have primary key. this is called as RDBMS.
Thanks

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.

create a foreign key on a primary key of another table

CREATE TABLE public.impiegato(
CF varchar NOT NULL,
codice_reparto int4 NOT NULL,
mansione varchar NULL,
CONSTRAINT impiegato_pkey PRIMARY KEY (CF),
CONSTRAINT impiegato_fkey FOREIGN KEY (codice_reparto) REFERENCES reparto(codice),
);
CREATE TABLE public.reparto(
codice int4 NOT NULL,
nome varchar NULL,
cf_responsabile varchar NULL,
nome_responsabile varchar NULL UNIQUE,
CONSTRAINT reparto_pkey PRIMARY KEY (codice),
CONSTRAINT reparto_cf_responsabile_fkey FOREIGN KEY (cf_responsabile) REFERENCES impiegato(CF)
);
When i run the sql code it tells me that the impiegato table doesn't exist. Can I run a foreign key on a primary key of another table?
The referenced table must exists when a foreign key is declared.
Since in your case the two tables reference each other, it's not possible to solve this by simply creating the right one first.
You have to create the first one (any of them) first without the foreign key constraint, create the second on and then add the foreign key constraint to the first one.
Something along the lines of:
CREATE TABLE public.impiegato
(cf varchar
NOT NULL,
codice_reparto int4
NOT NULL,
mansione varchar
NULL,
CONSTRAINT impiegato_pkey
PRIMARY KEY (cf));
CREATE TABLE public.reparto
(codice int4
NOT NULL,
nome varchar
NULL,
cf_responsabile varchar
NULL,
nome_responsabile varchar
NULL
UNIQUE,
CONSTRAINT reparto_pkey
PRIMARY KEY (codice),
CONSTRAINT reparto_cf_responsabile_fkey
FOREIGN KEY (cf_responsabile)
REFERENCES impiegato
(cf));
ALTER TABLE public.impiegato
ADD CONSTRAINT impiegato_fkey
FOREIGN KEY (codice_reparto)
REFERENCES reparto
(codice);
Unfortunately, you didn't tag your DBMS. From some details I guessed it might be Postgres and the code above hence is Postgres code. If you don't use Postgres, you might need to adapt the ALTER TABLE statement, they can differ between DBMS.

ERROR: violates foreign key constraint, key is not present in parent table (but it is??)

I know this question has been asked many times, but none of the answers have solved my issue.
I am creating a database for a uni assignment, using PostgreSQL through pgadmin 4, and I have a table named "staff" populated with staff members with a primary key of "staffid". I then have another table named "client_international", which includes a foreign key of "staffid" which relates to the staff tables primary key.
When trying to insert into the client table, I am getting the following error:
ERROR: insert or update on table "client_international" violates foreign key constraint "intclient_staff_fkey"
DETAIL: Key (staffid)=(100000024) is not present in table "staff".
SQL state: 23503
I am certain that that '100000024' key is in the staff table.. yet I still get the error. Any suggestions? Below I will paste the code I used to create the staff and client tables, in case anyone notices an error in them.
Staff table:
CREATE SEQUENCE staff_seq
start 100000000
increment 1;
CREATE TABLE staff
(
staffid integer default nextval('staff_seq'),
firstname varchar(20) NOT NULL,
lastname varchar(20) NOT NULL,
"position" varchar(20) NOT NULL,
mobile varchar(20) NOT NULL,
email varchar(100) NOT NULL,
"location" integer NOT NULL,
CONSTRAINT staff_pkey PRIMARY KEY (staffid)
);
Client table:
CREATE SEQUENCE client_seq
start 200000000
increment 1;
CREATE TABLE client
(
clientid integer default nextval('client_seq'),
company varchar(100) NOT NULL,
sector varchar(100) NOT NULL,
pointofcontact varchar(20) NOT NULL,
mobile varchar(20) NOT NULL,
email varchar(100) NOT NULL,
approvalstatus boolean default (false),
"location" integer NOT NULL,
staffid integer NOT NULL,
CONSTRAINT client_pkey PRIMARY KEY (clientid)
);
CREATE TABLE client_international
(
CONSTRAINT client_international_pkey PRIMARY KEY (clientid)
) INHERITS ("client");
ALTER TABLE client
ADD CONSTRAINT client_location_fkey FOREIGN KEY ("location") REFERENCES "location" (locationid),
ADD CONSTRAINT client_staff_fkey FOREIGN KEY (staffid) REFERENCES staff (staffid);
ALTER TABLE client_international
ADD CONSTRAINT intclient_location_fkey FOREIGN KEY ("location") REFERENCES "location" (locationid),
ADD CONSTRAINT intclient_staff_fkey FOREIGN KEY (staffid) REFERENCES staff (staffid);
I get the error when running the following statements:
INSERT INTO client_international(company, sector, pointofcontact, mobile, email, approvalstatus, "location", staffid)
VALUES ('Moores Dogs', 'Border Patrol', 'Carol Moore', '07911 653453', 'jenkinsj#k9solutions.co.uk', 'false', '500000001', '100000024');
Here's a screenshot of the entry in the staff table, showing that it's definitely in there:
Foreign keys aren't "inherited".
Quote from the manual
A serious limitation of the inheritance feature is that [...] foreign key constraints only apply to single tables, not to their inheritance children. This is true on both the referencing and referenced sides of a foreign key constraint.
(emphasis mine)
So what you are trying to do, simply isn't supported.

Recursive relationship SQL error

I am pretty new to SQL and I have a problem. I want to make a recursive relationship (a table that relates to itself), but I get an error when I try to execute my code. It's working fine without the Coordinator_Office_ID foreign key.
The error is:
The number of columns in the foreign-key referencing list is not equal
to the number of columns in the referenced list.
Create table Logistican (
Office_ID Number(10) Constraint nb_office Not NULL,
Worker_ID Number(15) Constraint lg_worker not null,
Name_logistican Varchar(20),
Room Varchar(10) constraint log_room UNIQUE,
Coordinator_Office_ID Integer,
Primary key (Office_ID, Worker_ID),
Constraint work_id Foreign key (Worker_ID) References worker(worker_ID) on delete cascade,
Constraint lg_cord_id Foreign key (Coordinator_Office_ID) References Logistican(Office_ID)
);
Yes, that's cause you have defined composite primary key like Primary key (Office_ID, Worker_ID) and thus your FK should include both of them else it will result in PFD (partial functional dependency)
Add the constraint with alter table:
Create table Logistican (
Office_ID Number(10) Constraint nb_office Not NULL,
Worker_ID Number(15) Constraint lg_worker not null,
Name_logistican Varchar(20),
Room Varchar(10) constraint log_room UNIQUE,
Coordinator_Office_ID Integer,
Primary key (Office_ID, Worker_ID),
Constraint work_id Foreign key (Worker_ID) References worker(worker_ID) on delete cascade
);
alter table Logistican
add Constraint lg_cord_id
Foreign key (Coordinator_Office_ID, Worker_Id) References Logistican(Office_ID, Worker_Id);
The relationship needs all elements of the primary key to be valid. I'm not sure if it needs to be a separate statement in Oracle.

Error There are no primary or candidate keys in the referenced table

I'm getting this error when trying to create a table with foreign key:
There are no primary or candidate keys in the referenced table 'TeamToPlayers' that match the referencing column list in the foreign key 'FKey2'.
I don't understand why, there is a primary key in the table TeamToPlayers.
Here are the queries:
create table TeamToPlayers
(TeamName varchar(50) NOT NULL,
PlayerName varchar(50) NOT NULL,
primary key(TeamName,PlayerName),
CONSTRAINT FKey FOREIGN KEY (TeamName) REFERENCES Teams(TeamName)
)
create table Players
(PlayerName varchar(50) NOT NULL,
primary key(PlayerName),
CONSTRAINT FKey2 FOREIGN KEY (PlayerName) REFERENCES TeamToPlayers(PlayerName)
);
Table TeamToPlayers primary key consists of two fields - you must reference both as otherwise it's not a key. I think you may have your key the wrong way round - it should be on TeamToPlayers and referencing Players like so:
create table TeamToPlayers
(
TeamName varchar(50) NOT NULL,
PlayerName varchar(50) NOT NULL,
primary key(TeamName,PlayerName),
CONSTRAINT FKey FOREIGN KEY (TeamName) REFERENCES Teams(TeamName),
CONSTRAINT FKey2 FOREIGN KEY (PlayerName) REFERENCES Players(PlayerName)
)
create table Players
(PlayerName varchar(50) NOT NULL,
primary key(PlayerName),
);