Using foreign keys with multiple tables - sql

I have a problem with creating a database. My fictional problem is to create database for tracking volleyball games. It should contain information about players (team they play in, one player can play only in one team), and played games( every game contains 6 players in each team).
I wanted to create following tables :
Player(Id P,Name,Surname,Team_Name F) ;
Team(Team_Name P,Coach);
Game(Date, Team1 F,Team2 F,Player1_Team1 F,...Player2_Team2 F,Player1_Team2 F,...,Player2_Team2 F).
I wanted that Team1 and Team2 are foreign keys Team_Name from Team table. Here is my attempt, I get that foreign key is incorrectly formed. I will be very glad for help.
CREATE TABLE Team (
Team_Name varchar(20) NOT NULL,
Coach varchar(20) NOT NULL,
CONSTRAINT Team_pk PRIMARY KEY (Team_Name)
);
CREATE TABLE Game (
id int NOT NULL,
Data date NOT NULL,
Team1 varchar(20) NOT NULL,
Team2 varchar(20) NOT NULL,
Score int ,
D1_Player1 int NOT NULL,
D1_Player2 int NOT NULL,
D1_Player3 int NOT NULL,
D1_Player4 int NOT NULL,
D1_Player5 int NOT NULL,
D1_Player6 int NOT NULL,
D2_Player1 int NOT NULL,
D2_Player2 int NOT NULL,
D2_Player3 int NOT NULL,
D2_Player4 int NOT NULL,
D2_Player5 int NOT NULL,
D2_Player6 int NOT NULL,
CONSTRAINT Game_pk PRIMARY KEY (id)
);
CREATE TABLE Player (
Id int NOT NULL,
Name varchar(30) NOT NULL,
Surname varchar(30) NOT NULL,
Team_Name varchar(20) NOT NULL,
CONSTRAINT Player_pk PRIMARY KEY (id)
);
ALTER TABLE Player ADD CONSTRAINT DZ
FOREIGN KEY (Team_Name)
REFERENCES Team (Team_Name)
;
ALTER TABLE Game ADD CONSTRAINT MD
FOREIGN KEY (Team1, Team2)
REFERENCES Team (Team_Name, Team_Name)
;
ALTER TABLE Mecz ADD CONSTRAINT MZ
FOREIGN KEY (D1_Player1, D1_Player2, D1_Player3, D1_Player4, D1_zPlayer5, D1_Player6, D2_Player1, D2_Player2, D2_Player3, D2_Player4, D2_Player5, D2_Player6)
REFERENCES Player (id, id, id, id, id, id, id, id, id, id, id, id)
;

You should add one by one all foreign keys.
ALTER TABLE Game ADD CONSTRAINT MZ
FOREIGN KEY (D1_Player1)
REFERENCES Player (id)
;
ALTER TABLE Game ADD CONSTRAINT MZ2
FOREIGN KEY (D1_Player2)
REFERENCES Player (id)
;
ALTER TABLE Game ADD CONSTRAINT MZ3
FOREIGN KEY (D1_Player3)
REFERENCES Player (id)
;
GO
✓
dbfiddle here

Related

How primary key in one table connect to other table with the same primary key?

How primary key in one table connect to another table with the same primary key?
I am trying to make it like this, which those two primary key in the table of CustomerCreditCard is connect to the table of Customer and table of Credit card]
https://i.stack.imgur.com/lIBUE.png
--3
CREATE TABLE Customer
(
CustomerID INT IDENTITY PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
);
--5
CREATE TABLE CreditCard
(
CreditCardNumber VARCHAR(16) PRIMARY KEY,
CreditCardOwnerName VARCHAR(50) NOT NULL,
);
--6
CREATE TABLE CustomerCreditCard
(
CreditCardNumber VARCHAR(16) NOT NULL,
CustomerID INT IDENTITY NOT NULL,
PRIMARY KEY(CreditCardNumber, CustomerID)
);
--6
CREATE TABLE CustomerCreditCard
(
CreditCardNumber VARCHAR(16) NOT NULL,
CustomerID INT NOT NULL,
CONSTRAINT pk_CustomerCreditCard
PRIMARY KEY(CreditCardNumber,CustomerID ),
CONSTRAINT fk_CustomerCreditCard_CreditCardNumber
FOREIGN KEY(CreditCardNumber)
REFERENCES CreditCard(CreditCardNumber)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT fk_CustomerCreditCard_CustomerID
FOREIGN KEY(CustomerID)
REFERENCES Customer(CustomerID)
ON DELETE CASCADE ON UPDATE CASCADE
);
To solve the problem of this question, add the foreign key to the table that has two primary keys, then reference to other tables that you want to connect with the same primary key.

SQL, Delete Records Based On Related Fields In Other Table

I have a SQL table based on hotel data. I have two tables and a bridge table to relate them. I'm still learning so I'm sure some of this is not ideal or has potential risks.
Guest Table
CREATE TABLE Guest
(
Guest_ID INT PRIMARY KEY IDENTITY (1, 1),
GuestName NVARCHAR(60) NOT NULL,
Street NVARCHAR(50) NOT NULL,
City NCHAR(30) NOT NULL,
[State] CHAR(2) NOT NULL,
CONSTRAINT [State.State]
FOREIGN KEY ([State]) REFERENCES [State]([State]),
Zip CHAR(5) NOT NULL,
Phone VARCHAR(15) NOT NULL
);
Room Table
CREATE TABLE Room
(
Room_ID SMALLINT PRIMARY KEY,
Room_Type_ID SMALLINT NOT NULL,
CONSTRAINT Room_Type_ID
FOREIGN KEY (Room_Type_ID) REFERENCES Room_Type([Type_ID]),
Amenity_Type_ID SMALLINT NOT NULL,
CONSTRAINT Amenity_Type_ID
FOREIGN KEY (Amenity_Type_ID) REFERENCES Amenity_Type([Type_ID])
);
Bridge Table (Reservations)
CREATE TABLE Guest_Bridge_Rooms
(
Guest_ID INT NOT NULL,
CONSTRAINT Guest_ID
FOREIGN KEY (Guest_ID) REFERENCES Guest(Guest_ID),
Room_ID SMALLINT NOT NULL,
CONSTRAINT Room_ID
FOREIGN KEY (Room_ID) REFERENCES Room(Room_ID),
Date_Start DATE NOT NULL,
Date_End DATE NOT NULL,
Occ_Adults SMALLINT NOT NULL,
Occ_Children SMALLINT NOT NULL,
Price_Total DECIMAL(13,2) NOT NULL
);
Now with these tables, I would like to write a script to DELETE all rows where a reservation (bridged table) has a specific guest NAME by somehow relating the given Guest_ID to its GuestName in the related table. I could simply use Guest_ID but that is not the goal here.
For example something like
DELETE FROM Guest_Bridge_Rooms
WHERE Guest[ID].GuestName = 'John Doe';
Is there a simple way to do this?
You can use a subquery:
DELETE FROM Guest_Bridge_Rooms
WHERE Guest_ID = (SELECT g.Guest_Id FROM Guests g WHERE g.GuestName = 'John Doe');
Note: The exact syntax might vary, depending on the database. This also assumes that GuestName is unique in Guests.

There is no unique constraint matching given keys for referenced table " exam_subjects"

CREATE TABLE student
(
student_id INT PRIMARY KEY,
first_name VARCHAR(40) NOT NULL,
last_name VARCHAR(40) NOT NULL,
birth_day DATE NOT NULL,
sex VARCHAR(1) NOT NULL,
student_email_address VARCHAR(40) NOT NULL UNIQUE,
student_password VARCHAR(10) NOT NULL UNIQUE,
student_nick_name VARCHAR(10) NOT NULL,
student_qualification VARCHAR(10) NOT NULL,
student_documents VARCHAR(255) NOT NULL,
student_image VARCHAR(100) NOT NULL
);
CREATE TABLE student_feedback
(
sr_no BIGSERIAL PRIMARY KEY,
student_id INT NOT NULL,
feedback_type VARCHAR(10) NOT NULL,
feedback_text VARCHAR(200) NOT NULL,
FOREIGN KEY (student_id) REFERENCES student(student_id)
);
CREATE TABLE online_exam
(
exam_id INT PRIMARY KEY,
exam_title VARCHAR(20) UNIQUE NOT NULL,
exam_duration_min INT NOT NULL,
total_questions INT NOT NULL,
marks_per_right_answer INT NOT NULL,
marks_per_wrong_answer INT NOT NULL,
passing_marks INT NOT NULL,
exam_status VARCHAR(2)
);
CREATE TABLE exam_subjects
(
sub_id INT,
exam_id INT,
sub_name VARCHAR(20) NOT NULL,
sub_desc VARCHAR(20) NOT NULL,
UNIQUE(sub_id,exam_id),
PRIMARY KEY(sub_id,exam_id),
FOREIGN KEY (exam_id) REFERENCES online_exam(exam_id) ON DELETE CASCADE
);
CREATE TABLE sub_questions
(
sub_id1 INT,
ques_id INT,
ques_text VARCHAR(150) NOT NULL,
ques_attachments VARCHAR(255),
option_1 VARCHAR(20) NOT NULL,
option_2 VARCHAR(20) NOT NULL,
option_3 VARCHAR(20) NOT NULL,
option_4 VARCHAR(20) NOT NULL,
UNIQUE(sub_id1,ques_id),
PRIMARY KEY (sub_id1,ques_id),
FOREIGN KEY (sub_id1) REFERENCES exam_subjects(sub_id) ON DELETE CASCADE
);
CREATE TABLE ques_answers
(
ans_id INT,
ques_id INT,
ans VARCHAR(20) NOT NULL,
PRIMARY KEY (ans_id,ques_id),
FOREIGN KEY (ques_id) REFERENCES sub_questions(ques_id) ON DELETE CASCADE
);
CREATE TABLE exam_registration
(
student_id INT,
exam_id INT,
exam_date_time TIMESTAMP NOT NULL,
PRIMARY KEY (student_id,exam_id),
FOREIGN KEY (student_id) REFERENCES student(student_id) ON DELETE CASCADE,
FOREIGN KEY (exam_id) REFERENCES online_exam(exam_id) ON DELETE CASCADE
);
CREATE TABLE exam_result
(
student_id INT,
exam_id INT,
sub_id INT,
marks_scored INT NOT NULL,
correct_ques INT NOT NULL,
wrong_ques INT NOT NULL,
grade VARCHAR(10) NOT NULL,
PRIMARY KEY(student_id,exam_id,sub_id),
FOREIGN KEY (student_id) REFERENCES student(student_id) ON DELETE CASCADE,
FOREIGN KEY (exam_id) REFERENCES online_exam(exam_id) ON DELETE CASCADE,
FOREIGN KEY (sub_id) REFERENCES exam_subjects(sub_id) ON DELETE CASCADE
);
Output :
CREATE TABLE,
CREATE TABLE,
CREATE TABLE,
CREATE TABLE,
There is no unique constraint matching given keys for referenced table "exam_subjects", relation "sub_questions" do not exist,
CREATE TABLE,
There is no unique constraint matching given keys for referenced table "exam_subjects".
Why am I getting "there is no unique..." error in postgresql? How to solve it? Please help.
In your table exam_subjects the primary key is a compossed key (PRIMARY KEY(sub_id, exam_id))
Therefore, your table sub_questions must have both columns to create the constraint, otherwise you get the error about unique constraints (or you can create a unique field acting as primary key, and create a unique index on both columns sub_id and exam_id)

SQL Missing left/right parenthesis

I keep getting a missing right or left parenthesis error when I try to create my tables with a foreign key, but when I remove the foreign key my code has no problem creating the tables. I need the code to run with the foreign keys.
--deletes respective tables previously created
drop table DEPARTMENT;
drop table POSITION;
drop table EMPLOYEE;
drop table COMPANY;
drop table DEGREE;
drop table GRAD_INFO;
drop table STUDENT;
CREATE TABLE Department
(
Dept_Name varchar(255) PRIMARY KEY, --primary key
Dept_Phone_Num numeric(35) not null
);
CREATE TABLE Position
(
Position_Name varchar(255) NOT NULL PRIMARY KEY, --primary key
Position_Salary decimal(10, 2) not null,
Employee_num numeric(35) not null,
CONSTRAINT fk_Dept_Name
FOREIGN KEY Dept_Name REFERENCES Department (Dept_Name) --foreign key
);
CREATE TABLE Employee
(
EmployeeID INT NOT NULL PRIMARY KEY, --primary key
Employee_Salary DECIMAL(10,2) DEFAULT NULL,
Employee_FName VARCHAR(30) DEFAULT NULL,
Employee_LName VARCHAR(30) NOT NULL,
Employee_Address VARCHAR(30) DEFAULT NULL,
Employee_Phone_Num INT(10) DEFAULT NULL,
Employee_Email VARCHAR(30) NOT NULL,
Employee_Status VARCHAR(10) NOT NULL,
CONSTRAINT Position_Name
FOREIGN KEY Position_Name REFERENCES Position(Position_Name), --foreign key
CONSTRAINT fk_Dept_Name
FOREIGN KEY Dept_Name REFERENCES Department(Dept_Name) --foreign key
);
CREATE TABLE Company
(
Comp_Name VARCHAR(20) NOT NULL PRIMARY KEY, --primary key
Position_Offer VARCHAR(30) NOT NULL,
Salary_Offer DECIMAL(10,2) NOT NULL,
Signing_Bonus DECIMAL(10,2) DEFAULT NULL,
Comp_Phone_Num INT(10) NOT NULL,
Comp_Address VARCHAR(30) NOT NULL,
CONSTRAINT fk_Employee_ID
FOREIGN KEY Employee_ID REFERENCES Employee (Employee_ID), --foreign key
CONSTRAINT fk_Dept_Name
FOREIGN KEY Dept_Name REFERENCES Department (Dept_Name) --foreign key
);
CREATE TABLE Degree
(
Degree_Type varchar(255) PRIMARY KEY, --primary key
Academic_Status varchar(255) not null,
Academic_Level varchar(255) not null,
Major varchar(255) not null,
Minor varchar(255) default null
);
CREATE TABLE Gead_Info
(
Grad_Status VARCHAR(255) NOT NULL PRIMARY KEY, --primary key
College_Name VARCHAR(255) NOT NULL,
Num_Of_Degrees NUMERIC(10) NOT NULL,
Grad_Date NUMERIC(6) NOT NULL,
CONSTRAINT fk_Degree_Type
FOREIGN KEY Degree_Type REFERENCES Degree(Degree_Type) --foreign key
);
CREATE TABLE Student
(
Student_ID NUMERIC(10) NOT NULL PRIMARY KEY, --primary key
Student_FName VARCHAR(20) NOT NULL,
Student_LName VARCHAR(20) NOT NULL,
Student_Address VARCHAR(20) NOT NULL,
Student_Email VARCHAR(20) NOT NULL,
Student_Phone_Num VARCHAR(10) NOT NULL,
CONSTRAINT fk_Comp_Name
FOREIGN KEY Comp_Name REFERENCES Company(Comp_Name), --foreign key
CONSTRAINT fk_Grad_Status
FOREIGN KEY Grad_Status REFERENCES Gead_Info(Grad_Status) --foreign key
);
The degree table is the only table where I don't get an error.
Should I use an alter table instead after I create all the tables or is there another way to solve my problem?
edit: updated code
I think your most immediate issue is with the Department table not having a comma between the two CONSTRAINT clauses. You might also run into issues with your Position table's CONSTRAINT clause referencing the Position table instead of the Employee table, although honestly I don't think you need that relationship defined at all since the Employee table already has a foreign key constraint with Position. And like what was stated earlier, your table definitions aren't in the right order so you have some tables referencing other tables before those others are created.
Give this a shot to see if the syntax works. I've added the column definition for the foreign key in Position, put parentheses around the foreign key column name in the CONSTRAINT clause, and removed the space between Department and the left paren in the CONSTRAINT clause. If this script works, make the same changes to your other table defs.
CREATE TABLE Department(
Dept_Name varchar(255) Primary Key, --primary key
Dept_Phone_Num numeric(35) not null
);
CREATE TABLE Position(
Position_Name varchar(255) not null Primary Key, --primary key
Position_Salary decimal(10, 2) not null,
Employee_num numeric(35) not null,
Dept_Name varchar(255) not null,
CONSTRAINT fk_Dept_Name FOREIGN KEY (Dept_Name) REFERENCES Department(Dept_Name) --foreign key
);

Oracle SQL constraint, name entered must be a member

I have created a tennis club database. This database contains the following tables:
The player table
CREATE TABLE player
(
member_id INT PRIMARY KEY NOT NULL,
member_name VARCHAR2(70) NOT NULL,
date_of_birth DATE,
member_address VARCHAR2(300),
contact_number INT NOT NULL,
gender VARCHAR2(1) NOT NULL CHECK(gender IN('f','m')),
club_seeding INT NOT NULL,
county_seeding INT NOT NULL,
renewal_date DATE,
m_type VARCHAR(9) NOT NULL CHECK(m_type IN('junior','student', 'senior', 'family', 'associate'))
);
This consists of members of the tennis club.
And then there is the team table
CREATE TABLE team
(
team_id INT PRIMARY KEY NOT NULL,
club_seeding INT,
county_seeding INT,
player1 VARCHAR2(70) NOT NULL,
player2 VARCHAR2(70) NOT NULL,
team_name VARCHAR2(145) NOT NULL
);
This is used to enter 2 players to form a doubles team.
My question is how could I create a constraint that only allows players(member_name) from the player table to be entered into the team table?
you need create foreign key constraints
see docs here
but in your sample you need change type of player1 and player2 columns from varchar to int:
sample of alter table statements
-- Create foreign key constraints
alter table TEAM
add constraint fk_team_player_1 foreign key (PLAYER1)
references player (MEMBER_ID);
alter table TEAM
add constraint fk_team_player_2 foreign key (PLAYER2)
references player (MEMBER_ID);
sample of createing FK contstraints in table
CREATE TABLE team
(
team_id INT PRIMARY KEY NOT NULL,
club_seeding INT,
county_seeding INT,
player1 INT NOT NULL,
player2 INT NOT NULL,
team_name VARCHAR2(145) NOT NULL
,constraint fk_team_player_1 foreign key (PLAYER1)
references player (MEMBER_ID)
,constraint fk_team_player_2 foreign key (PLAYER2)
references player (MEMBER_ID)
);
if you want to use member names as PK
CREATE TABLE player
(
member_name VARCHAR2(70) PRIMARY KEY NOT NULL,
date_of_birth DATE,
member_address VARCHAR2(300),
contact_number INT NOT NULL,
gender VARCHAR2(1) NOT NULL CHECK(gender IN('f','m')),
club_seeding INT NOT NULL,
county_seeding INT NOT NULL,
renewal_date DATE,
m_type VARCHAR(9) NOT NULL CHECK(m_type IN('junior','student', 'senior', 'family', 'associate'))
);
CREATE TABLE team
(
team_id INT PRIMARY KEY NOT NULL,
club_seeding INT,
county_seeding INT,
player1 VARCHAR2(70) NOT NULL,
player2 VARCHAR2(70) NOT NULL,
team_name VARCHAR2(145) NOT NULL
,constraint fk_team_player_1 foreign key (PLAYER1)
references player (member_name)
,constraint fk_team_player_2 foreign key (PLAYER2)
references player (member_name)
);