create a foreign key on a primary key of another table - sql

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.

Related

Setting up indexes for multiple foreign keys

An error message regarding indexes displays when foreign keys are added using the following scripts. I have added primary keys and indexes different ways but not sure if the diagram is providing information about how to setup the indexes/primary keys that I'm not seeing.
CREATE TABLE aocommercial_building(
parcel CHAR(25) NOT NULL,
suffix INT NOT NULL,
owner VARCHAR(255) NULL,
owner2 VARCHAR(255) NULL,
);
CREATE TABLE aocommercial_heatcool(
parcel CHAR(25) NOT NULL,
suffix INT NOT NULL,
section INT NULL,
heat_cool_cd VARCHAR(255) NULL
);
CREATE TABLE aocommercial_unit(
parcel CHAR(25) NOT NULL,
suffix INT NOT NULL,
section INT NOT NULL,
occ_desc VARCHAR(255) NULL
);
CREATE TABLE aocom_misc_bldg(
parcel CHAR(25) NOT NULL,
suffix INT NOT NULL,
section INT NOT NULL,
misc_bldg_type VARCHAR(255) NULL
);
ALTER TABLE aocommercial_unit ADD FOREIGN KEY (parcel) REFERENCES aocommercial_building(parcel);
ALTER TABLE aocommercial_unit ADD FOREIGN KEY (suffix) REFERENCES aocommercial_building(suffix);
ALTER TABLE aocommercial_heatcool ADD FOREIGN KEY (parcel) REFERENCES aocommercial_unit(parcel);
ALTER TABLE aocommercial_heatcool ADD FOREIGN KEY (suffix) REFERENCES aocommercial_unit(suffix);
ALTER TABLE aocommercial_heatcool ADD FOREIGN KEY (section) REFERENCES aocommercial_unit(section);
ALTER TABLE aocom_misc_bldg ADD FOREIGN KEY (parcel) REFERENCES aocommercial_unit(parcel);
ALTER TABLE aocom_misc_bldg ADD FOREIGN KEY (suffix) REFERENCES aocommercial_unit(suffix);
ALTER TABLE aocom_misc_bldg ADD FOREIGN KEY (section) REFERENCES aocommercial_unit(section);
enter image description here
For each table, what column (or combination of columns) uniquely identifies each row? Then, include in each CREATE TABLE another line with PRIMARY KEY(...).
For each table, if there is no particular set of columns to uniquely define each row, then add
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id)
Look around; there are lots and lots of examples.

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

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

CONSTRAINT to foreign keys to one table - causes error

I am starting to build something like system up to the just cooperate with suggestions coming into the database called ForslagOpslag.
Every time I try to update table with likes, you will see it with this one error:
Update cannot proceed due to validation errors. Please correct the following errors and try again.
SQL71516 :: The referenced table '[dbo].[ForslagOpslag]' 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.
Here is how I built my ForslagOpslagLikes table:
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_ToGetid]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id]),
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslag]([fk_brugerid])
);
Reason I have both fk_brugerid and getid is for sure me that the user can not vote / like more once!
The way I have built my ForslagOpslag table:
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR (MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
like this to be my like system do:
ForslagOpslagLikes -> fk_brugerid to ForslagOpslag -> fk_brugerid
ForslagOpslagLikes -> getid to ForslagOpslag -> id
Well - the error seems pretty clear: you're trying to estabslish a foreign key relationship to ForslagOpslag.fk_brugerid here:
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslag]([fk_brugerid])
but that column is NOT the primary key of that other table - and it's not a UNIQUE constraint either - so you cannot reference that column in a foreign key relationship.
But the column(s) that a foreign key references must be the primary key of that other table - or in SQL Server, it's good enough if there's a UNIQUE constraint on that column. You must ensure that the values you reference in FroslagOpslag only match a single column in that table - otherwise, you cannot establish a foreign key relationship
Try to remove the foreing key in your first table like this
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_ToGetid]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id]),
);
Then you need to add the foreign key in the second table with the primary key with the first table
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR (MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslagLikes]([fk_brugerid])
);
You sound scandinavian, and Bruger means User (for all the non-scandinavians here).
What you appear to want is a Bruger (User) table, where fk_brugerid in ForslagOpslag is the user who created the record with opretdato being the creation date, and ForslagOpslagLikes is an association table of users who likes the ForslagOpslag with opretdato being the date they clicked on "Like".
CREATE TABLE [dbo].[Bruger]
(
[brugerid] INT IDENTITY (1, 1) NOT NULL,
...,
CONSTRAINT [PK_Bruger]
PRIMARY KEY CLUSTERED ([brugerid])
);
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR(MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
CONSTRAINT [PK_ForslagOpslag]
PRIMARY KEY CLUSTERED ([Id]),
CONSTRAINT [FK_ForslagOpslag_Bruger]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[Bruger] ([brugerid])
);
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_Bruger]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[Bruger] ([brugerid]),
CONSTRAINT [FK_ForslagOpslagLikes_ForslagOpslag]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id])
);

Oracle: Many to Many: Requires two Foreign Key Constraints?

Im very new to SQL and i tried to create a many to many relationship:
CREATE TABLE HOUSE_USER
(
USER_ID NUMBER(10) NOT NULL,
USER_EMAIL VARCHAR(255) NOT NULL,
USER_PASSWORD VARCHAR(255) NOT NULL,
CONSTRAINT USER_PK PRIMARY KEY(USER_ID),
CONSTRAINT PROFILE_FK FOREIGN KEY(PROFILE_ID) REFERENCES HOUSE_PROFILE(PROFILE_ID)
);
CREATE TABLE HOUSE_USER_GROUPE
(
USER_GROUPE_ID NUMBER(10) NOT NULL,
USER_GROUPE_NAME VARCHAR(255) NOT NULL,
CONSTRAINT USER_GROUPE_PK PRIMARY KEY(USER_GROUPE_ID)
);
CREATE TABLE HOUSE_USER_USER_GROUPE
(
USER_ID NUMBER(10) NOT NULL,
USER_GROUPE_ID NUMBER(10) NOT NULL,
CONSTRAINT USER_USER_GROUPE_PK PRIMARY KEY(USER_ID, USER_GROUPE_ID),
CONSTRAINT USER_FK FOREIGN KEY(USER_ID) REFERENCES HOUSE_USER(USER_ID),
CONSTRAINT USER_GROUPE_FK FOREIGN KEY(USER_GROUPE_ID) REFERENCES HOUSE_USER_GROUPE(USER_GROUPE_ID)
);
I need to ask now if these two constraints:
CONSTRAINT USER_FK FOREIGN KEY(USER_ID) REFERENCES HOUSE_USER(USER_ID),
CONSTRAINT USER_GROUPE_FK FOREIGN KEY(USER_GROUPE_ID) REFERENCES
are neccessary or not. I ask because i have another many to many relationship:
CREATE TABLE HOUSE_USER_GROUPE
(
USER_GROUPE_ID NUMBER(10) NOT NULL,
USER_GROUPE_NAME VARCHAR(255) NOT NULL,
CONSTRAINT USER_GROUPE_PK PRIMARY KEY(USER_GROUPE_ID)
);
CREATE TABLE HOUSE_ACCESSR
(
ACCESSR_ID NUMBER(10) NOT NULL,
ACCESSR_NAME VARCHAR(255) NOT NULL,
CONSTRAINT ACCESSR_PK PRIMARY KEY(ACCESSR_ID)
);
CREATE TABLE HOUSE_USER_GROUPE_ACCESR
(
USER_GROUPE_ID NUMBER(10) NOT NULL,
ACCESSR_ID NUMBER(10) NOT NULL,
CONSTRAINT USER_GROUPE_ACCESSR_PK PRIMARY KEY(USER_GROUPE_ID, ACCESSR_ID),
CONSTRAINT USER_GROUPE_FK FOREIGN KEY(USER_GROUPE_ID) REFERENCES HOUSE_USER_GROUPE(USER_GROUPE_ID),
CONSTRAINT ACCESSR_FK FOREIGN KEY(ACCESSR_ID) REFERENCES HOUSE_ACCESSR(ACCESSR_ID)
);
I cant create the second many to many table because i already used the constraint:
CONSTRAINT USER_GROUPE_FK FOREIGN KEY(USER_GROUPE_ID) REFERENCES HOUSE_USER_GROUPE(USER_GROUPE_ID),
I could just rename it but because of that error:
ORA-02264: name already used by an existing constraint
I just was wondering if these constraints are mandatory.
Yes, you should create the foreign key constrain on both tables.
The foreign key constraints are there to maintain referential integrity; ensuring that you can't insert values that don't exist in the parent table.
If you don't add the constraint to HOUSE_USER_GROUPE_ACCESR then you don't get that protection in that table. And you should want that protection everywhere.
Your only apparent mistake is that the constraint names are identical to each other. I traditionally either include No Name (letting Oracle decide on the name, because I never refer to the constraint by name) or use a format something like fk_<table>_<field>.
You need to do the constraints.. create the second constraints with another name.

SQL Syntax error with foreign keys

now i have table place CREATE TABLE [dbo].[Place] (
[Place_Id] INT IDENTITY (1, 1) NOT NULL,
[Name] VARCHAR (50) NOT NULL,
[Building_Date] DATE NULL,
[Longitude] VARCHAR (50) NULL,
[Latitude] VARCHAR (50) NULL,
[Location] VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Place_Id] ASC)
); , and table Citeria CREATE TABLE [dbo].[Criteria] (
[Criteria] VARCHAR (50) NOT NULL,
[Place_Id] INT NOT NULL, PRIMARY KEY CLUSTERED ([Criteria], [Place_Id]), CONSTRAINT [FK_Criteria_ToTable] FOREIGN KEY (Place_Id) REFERENCES Place(Place_Id)
);and The referenced table '[dbo].[Criteria]' 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.
.
The error is correct. Subqueries are not allowed in check constraints.
But, you already have a foreign key reference between user_name and likes(user_name), so this condition is already in place. The only thing is would really be checking is that user_name is not NULL, but that is already true by the definition of the column.
Now, there are other issues. Your foreign keys should be to primary keys or unique keys in other tables. I think this is your intention:
CREATE TABLE [dbo].Normal_Upload
(
[User_Name] VARCHAR(50) NOT NULL ,
[Place_Id] INT NOT NULL,
[Image] IMAGE NOT NULL,
CONSTRAINT [FK_Normal_Upload] FOREIGN KEY (User_Name) REFERENCES Member(User_Name),
CONSTRAINT [FK_Normal_Upload_1] FOREIGN KEY (Place_Id) REFERENCES Place(Place_Id),
CONSTRAINT [FK_Normal_Upload_2] FOREIGN KEY (User_Name, Place_Id) REFERENCES Likes(User_Name, Place_Id)
);
As a note on naming. I think the primary keys of tables should include the table name. So, consider Member_Name rather than User_Name for the Member table.
It wrong db design, never use varchar or character type column in reference key or primary-key(try to avoid as much as possible).
For you solution, create a column "useid" with int datatype and give pk to it. and update the following table
CREATE TABLE [dbo].[Likes] (
[User_id] VARCHAR (50) Identity (1,1),
[User_Name] VARCHAR (50) NOT NULL,
[Place_Id] INT NOT NULL,
CONSTRAINT [PK_Likes] PRIMARY KEY CLUSTERED ([User_id] ASC, [Place_Id] ASC),
CONSTRAINT [FK_Likes_ToTable] FOREIGN KEY ([User_Name]) REFERENCES Normal ([User_Name]),
CONSTRAINT [FK_Likes_ToTable_1] FOREIGN KEY ([Place_Id]) REFERENCES [dbo].[Place] ([Place_Id]),
);