Cross foreign key Postgresql - database

I need to create two tables such as:
Id_faculty_reference and Id_professor are primary keys (that works)
Id_dean is a foreign key with reference to Id_professor
Id_faculty is a foreign key with reference to Id_faculty_reference (the problem).
I tried this:
CREATE TABLE Faculty(
Id_faculty_reference int PRIMARY KEY,
faculty_name varchar,
Id_dean int
);
CREATE TABLE Professors(
Id_professor int PRIMARY KEY,
Name varchar,
Last_name varchar,
Salary int,
Id_faculty int REFERENCES Faculty(id_faculty_reference)
);
ALTER TABLE Faculty ADD FOREIGN KEY (Id_dean)
REFERENCES Professors(id_professor);
The problem comes when I try to add information into the tables. If I try to add info into Faculty, there is no reference, because Professors is empty:
Key is not present in table "Professors"
If I try to add info into Professors, there is no reference because Faculty is empty:
Key is not present in table "Faculty"
The mistake makes sense to me, but my professor says that what he asks can be done; how can I do this?

There are three approaches:
First insert a faculty where id_dean is NULL. Then insert a professors that references that faculty entry. Then update the first entry to point to the second.
This works because id_dean can be NULL, and a foreign key that is set to NULL is not enforced.
In general it is a good idea to have as many columns NOT NULL as possible. In that case use one of the other methods.
Foreign keys are checked at the end of the statement, so insert both rows in a single statement:
WITH newfac AS (
INSERT INTO faculty (...) VALUES (...)
RETURNING id
)
INSERT INTO professors (id_faculty, ...)
SELECT newfac.id, ...
FROM newfac;
Use a deferred foreign key constraint:
CREATE TABLE faculty(
...,
id_dean int REFERENCES professors DEFERRABLE INITIALLY DEFERRED
);
Such a foreign key constraint is not checked at the end of the statement, but at the end of the transaction. So you can first enter the faculty, then the professors, as long as you do it in a single database transaction.

Related

Table with multiple relations to a single primary key

Is it possible to create multiple relations from one table, to another table?
I have a table containing purchases, each of these purchases have a origin_country and a destination_country.
I would like to have relations (as foreign keys) to a single PK on a table from these two columns from the same table.
i have tried the following queries:
alter table Purchases
add constraint FK_Purchases_OriginCountries
foreign key (FK_OriginCountryCode) references dbo.countries
go
alter table Purchases
add constraint FK_Purchases_DestinationCountries
foreign key (FK_DestinationCountryCode) references dbo.countries
go
But end up getting a conflict, I can't however find documentation that this is not possible...
[23000][547] The ALTER TABLE statement conflicted with the FOREIGN KEY
constraint "FK_Purchases_DestinationCountries". The conflict occurred
in database "Market", table "dbo.countries", column 'ID'.
Is this relationship intentionally not possible, or did i just make a mistake?
Thank you
Yes you can.
The error is not a result of trying to create two foreign keys back to a single table, that's perfectly fine. Try running this to see it work:
create table t(i int primary key);
create table u
(
j int foreign key references t(i),
k int foreign key references t(i)
);
The problem you have is that you have some data in your Purchases table where the value in the column on which you are trying to create the foreign key does not exist in the countries table's ID column.
To find them run a query like this:
select p.*
from dbo.purchases p
where not exists
(
select *
from dbo.countries
where ID = p.FK_DestinationCountryCode
)
Note that I think your column names are a little weird here, You shouldn't call a column FK_DestinationCountryCode just because it has a foreign key on it, and a "code" is not the same kind of thing as an "ID". Your purchases table's columns should probably be called DestinationCountryID and OriginCountryID.

Entity Framework appears to skip mapping a table with a multi-column primary key set through a constraint

I've created an ADO.NET model via the database first approach.
One of my tables which is listed when creating the model doesn't actually get added to it.
The table has a multi-column primary key, composed of two foreign keys.
CREATE TABLE ForumAccess
(
UserID INT FOREIGN KEY REFERENCES Users(UserID) NOT NULL,
ForumID INT FOREIGN KEY REFERENCES Forums(ForumID) NOT NULL,
CONSTRAINT ForumAccessID PRIMARY KEY (UserID, ForumID),
);
It does show up when I have to select which tables to add, but then it seems to be skipped. No class is generated for it, and it's not shown in the .edmx file.
Part of my application depends on the existence of this table. I have another table which has a multi-column primary key, and another DateTime type column. That table does get added.
That table is:
CREATE TABLE Moderators
(
UserID INT FOREIGN KEY REFERENCES Users(UserID) NOT NULL,
ForumID INT FOREIGN KEY REFERENCES Forums(ForumID) NOT NULL,
TimeOfAddition DateTime NOT NULL, -- When the mod was added as a mod.
CONSTRAINT ModeratorID PRIMARY KEY (UserID, ForumID),
);
Why does the Moderators table get added, but the ForumAccess table doesn't?
There is no error, or any warning that I can see.
What am I missing?

T-SQL inserting data into table with foreign key

I'm using SQL Server 2014 to create and insert data into tables and came along a problem when it comes to populating a table with a foreign key constraint in it. I have a table user and and a table city which were created beforehand.
I used code to alter the user table to include a cityId foreign key from table city with this code:
ALTER TABLE [Schema].[user]
ADD cityId UNIQUEIDENTIFIER NOT NULL
CONSTRAINT usr_cid_fk
FOREIGN KEY (cityId) REFERENCES [Schema].[city] (cityId);
GO
Basically I modified the user table by adding a field called cityId which i made foreign key. now the problem is that when inserting data, in the first line
INSERT INTO [Schema].[user](name, surname, dob, gender, .. )
cityId cannot be found to be mapped. Dunno why it ain't showing. In the design view it is listed as a foreign key so there should be no problems.
Thanks a lot
try :
ALTER TABLE [Schema].[user]
ADD cityId NUMBER NOT NULL
CONSTRAINT usr_cid_fk
FOREIGN KEY (cityId) REFERENCES [Schema].[city] (cityId);
Note :
For ADD cityId UNIQUEIDENTIFIER NOT NULL
By the SQL standard, a foreign key must reference either the primary key or a unique key of the parent table. If the primary key has multiple columns, the foreign key must have the same number and order of columns. Therefore the foreign key references a unique row in the parent table; there can be no duplicates.

Extending SQL Table

I have 4 SQL tables: User, Student, Professor and Publication.
User has the common columns for any kind of user;
Student has columns specific for a student;
Professor has columns specific for a professor;
Publication is only for professors.
So I have:
create table dbo.[User] (
Id int identity not null
constraint PK_User_Id primary key clustered (Id),
-- Other user columns
)
create table dbo.Student (
UserId int not null
constraint PK_Student_UserId primary key clustered (Id),
-- Other student columns
)
create table dbo.Professor (
UserId int not null
constraint PK_Professor_Id primary key clustered (Id),
-- Other student columns
)
create table dbo.Publication (
Id int identity not null
constraint PK_Publication_Id primary key clustered (Id),
UserId int not null
-- Other student columns
)
alter table dbo.Student
add constraint FK_Student_UserId foreign key (UserId) references dbo.[User](Id);
alter table dbo.Professor
add constraint FK_Professor_UserId foreign key (UserId) references dbo.[User](Id);
alter table dbo.Publication
add constraint FK_Publication_UserId foreign key (UserId) references dbo.Professor(Id);
QUESTION
Should I have a column Id as PK in Professor and Student tables?
And make, for example, (Id, UserId) as the PK of Professor (Same for student)
Then Publication would reference Professor.Id and not Professor.UserId.
I am asking this because it sounds strange to have Publication to reference UserId from Professor table which can be confusing when I will have more tables.
Could someone please advice me on this?
In your current schema arrangement and without knowing your use cases (programmatically), one could make the argument that you don't need the Id identity columns for any of the extension tables. I assume this would be a 1 to 1 relationship to the User table anyway, so you'd at least want a unique constraint on the UserID columns, which you'd get by making it a PK anyway.
Things I like to consider are:
Can a professor ever become a different user ?
Is it possible for a professor to exist without an user ?
Is it possible for a single user to be two professors (multiple disciplines?)
If so, why wouldn't you give every professor an unique Id (ProfessorId), and only create a foreign key to the User table (UserId, you could call this UserFk).
In the publication table you can reference the professor by his/her id and call this one ProfessorFk. This way you create very efficient references between tables. The publication table than also gets a single PublicationId as primary key.
Correct me if i'm wrong, i don't know your use case. But it would seem reasonable that a professor can have multiple publications, but a publication can also be written by multiple professors ? This would mean you need an extra table between publication and professor for the n-n relationship.
About creating a professor key that is a combined key (Id, UserId). I personally dislike combined keys, if you want to reference this professor from your publication table you need two columns.
This would also suggest you can have multiple professors for the same user, if so, go for the single Id option.
This means i would create the following setup:
User Table
UserId
Student Table
StudentId
UserFk
Professor Table
ProfessorId
UserFk
ProfessorPublication Table
ProfessorFk
PublicationFk
Publication Table
PublicationId
So, it partly is based on what you want to be able to do with your data, and partly just your preference.

Postgres: two foreign keys to same primary key field

create table date_dimension (
id serial primary key,
date_id date,
..... others
);
create table temp (
id serial primary key,
from_date integer,
to_date integer,
value integer,
foreign key (from_date, to_date) references date_dimension(id, id)
);
How can I refer both from_date and to_date to id field in date_dimension?
The current code fails to do that saying
ERROR: there is no unique constraint matching given keys for referenced table "date_dimension"
Thank you
each FOREIGN KEY constraint added to a table will always relate one row in the referencing table to one row* in the referant. If you want to have each row in the referencing to refer to two distinct rows in the referant, you need two, separate foreign key constraints.
you want:
foreign key (from_date) references date_dimension(id)
foreign key (to_date) references date_dimension(id)
You almost always want to have exactly the rows in the foreign key to be the same as the primary key in the referant.
* Actually, there may be more than one row in the referant if the foreign key is smaller than a candidate key of the referant. this is seldom useful, though, and almost certainly unrelated to the problem you're describing

Resources