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

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.

Related

There are no primary or candidate keys in the referenced table 'tblgender' that match the referencing column list in the foreign key 'giFK'

create database my_data
create table tblperson(
pid int primary key,
pname varchar(15),
pgender varchar(15)
)
create table tblgender(
gid varchar(15) primary key,
gender varchar(15)
)
Alter table tblperson add constraint giFK
Foreign key (pgender) references tblgender(gid)

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
);

i getting this error: The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "foreign_key1"

CREATE TABLE singer(
name varchar(50) primary key,
email varchar(50) not null,
account_number varchar(50) not null,
balance int not null
);
create table song(
id int primary key,
name varchar(50) not null,
singer varchar(50) foreign key references singer,
producer varchar(50) not null,
album varchar(50) not null,
total_sell int not null
);
CREATE TABLE producer(name VARCHAR(20) PRIMARY KEY);
ALTER TABLE song ALTER COLUMN producer VARCHAR(20);
ALTER TABLE song ADD CONSTRAINT foreign_key1 FOREIGN KEY(producer) REFERENCES producer;
In MySQL you can use this:
CREATE TABLE producer(
name varchar(20),
PRIMARY KEY (name)
);
CREATE TABLE song(
id int,
name varchar(50) not null,
singer varchar(50) not null,
producer varchar(50) not null,
album varchar(50) not null,
total_sell int not null,
PRIMARY KEY (`id`),
CONSTRAINT `foreign_key1` FOREIGN KEY (`producer`) REFERENCES `producer` (`name`)
);
OR:
ALTER TABLE `song`
ADD CONSTRAINT `foreign_key1`
FOREIGN KEY (`producer`)
REFERENCES `producer` (`name`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
you can see Here.
I can advise you to declare the same length as the name column. es. varchar(50)

Alter Table syntax Assignment

I have Assignment due in which i'm stuck on a question.
Add a “Sales Detail” table to your database. This table is related to the Orders and Products tables. It shows the product and quantity ordered at least (add other fields if you wish but explain why you added them on your paper).
There is no description of this table on the diagram provided. Use your best database design skills here!
Create Table SalesDetail
(
SaleDetailID int,
ProductID char(5),
ManufactureID char(3) not null,
OrderNo int,
qtyOrdered int
PRIMARY
)
Alter Table SalesDetail
Add FOREIGN KEY (ProductID)
REFERENCES Products(ProductID)
My Error is I can not get it to link SalesDetail table to Products table.
Msg 1776, Level 16, State 0, Line 1
There are no primary or candidate keys in the referenced table 'Products' that match the referencing column list in the foreign key 'FK__SalesDeta__Produ__5EBF139D'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
Create Table Customers
(
CustomerNo char(4)
Constraint ck_CustomerNoHas4positionsWithNumbers
Check(CustomerNo like'[0-9],[0-9],[0-9],[0-9]'),
Company varchar(50) not null,
CustomerRep char(3),
CreditLimt money default(20000.00),
PRIMARY KEY(CustomerNo)
)
Create Table Salesreps
(
EmployeeNo char(3)
Constraint ck_EmployeeNoHasDigits check(EmployeeNo like'[0-9],[0-9],[0-9]'),
FirstName varchar(25) not null,
LastName varchar(25) not null,
Age int,
SalesRepOffice char(2) not null,
Title varchar(50),
HireDate Date not null,
Manager char(3) not null,
Quota money,
Sales money not null,
PRIMARY KEY(EmployeeNo)
)
Create Table Offices
(
Office char(2) Constraint ck_checkOfficeHasNumbersOnly check(Office like'[0-9],[0-9]'),
City varchar(25) not null,
Region varchar(10) not null,
Manager char(3) not null,
Target money,
Sales money not null
PRIMARY KEY(Office)
)
Create Table Orders
(
OrderNo int,
OrderDate Date not null,
CustomerNo char(4) not null,
SalesRep char(3) not null
PRIMARY KEY(OrderNo)
)
Create Table Products
(
ManufactureID char(3)
Constraint ck_ManufactureIDifItHasLettersOnly check(ManufactureID like'[a-z],[a-z],[a-z]'),
ProductID char(5)
Constraint ck_ProductIDhasTwoLettersAndThreeNumbers check(ProductID like'[0-9],[0-9],[a-z],[a-z],[a-z]'),
Description varchar(50) not null,
Price money not null,
QtyOnHand int not null,
PRIMARY KEY(ManufactureID, ProductID)
)
--Add Foreign Keys to all tables who needs them
Alter Table Customers
Add constraint fk_customerrep
FOREIGN KEY (CustomerRep)
REFERENCES Salesreps(EmployeeNo)
Alter Table Salesreps
Add constraint fk_salesrepoffice
FOREIGN KEY (SalesRepOffice)
REFERENCES Offices(Office),
constraint fk_manager
FOREIGN KEY (Manager)
REFERENCES Salesreps(EmployeeNo)
Alter Table Offices
Add constraint fk_officesmanger
FOREIGN KEY (Manager)
REFERENCES Salesreps(EmployeeNo)
Alter Table Orders
Add constraint fk_customerno
FOREIGN KEY (CustomerNo)
REFERENCES Customers(CustomerNo),
constraint fk_salesrep
FOREIGN KEY (SalesRep)
REFERENCES Salesreps(EmployeeNo)
The table Products has a composite key (ManufactureID, ProductID), so you cannot uniquely identify a product by just the ProductId. Therefore you have to create a composite foreign key that references to both ManufactureId and ProductID:
Alter Table SalesDetail
Add FOREIGN KEY (ManufactureId, ProductID)
REFERENCES Products(ManufactureID, ProductID)
ProductID is not a primary key like the error says. In your code
PRIMARY KEY(ManufactureID, ProductID)
This creates a primary key that both of those columns combined.
The primary key for Products is (ManufactureID, ProductID). So the SalesDetail table should contain both these columns, and both should be part of the foreign key constraint:
Alter Table SalesDetail
Add FOREIGN KEY (ManufactureID, ProductID)
REFERENCES Products(ManufactureID, ProductID)