Create and insert data with many to many relationaships - sql

I try one to many relationships in postgresql, but nothing
Here my wrong attempt
CREATE TABLE person_basic_info (
id INT NOT NULL PRIMARY KEY,
gender VARCHAR (50) NULL,
first_name VARCHAR (150) NULL,
last_name VARCHAR (150) NULL,
email VARCHAR (50) NULL,
political_view_id INT NULL,
cambridge_analytica_psychographics_id INT NULL REFERENCES persons_features (id),
revolution_sympathy int NULL,
iq_level INT NULL
);
Create person features
CREATE TABLE persons_features (
id INT NOT NULL PRIMARY KEY,
dominate_feature VARCHAR (100) NULL
);
--person_basic_info
insert into person_basic_info(id, gender, first_name, last_name, email, political_view_id, cambridge_analytica_psychographics_id,revolution_sympathy,iq_level) values (1,'Female','Corenda','Garrood','cgarrood0#yellowbook.com',6,2,0,86);
insert into person_basic_info(id,gender, first_name, last_name, email, political_view_id, cambridge_analytica_psychographics_id,revolution_sympathy,iq_level) values (2,'Male','Langston','McMychem','lmcmychem1#theatlantic.com',2,4,0,111);
insert into person_basic_info(id,gender, first_name, last_name, email, political_view_id, cambridge_analytica_psychographics_id,revolution_sympathy,iq_level) values (3,'Female','Robbyn','Imison','rimison2#geocities.com',14,3,1,98);
--persons_features
insert into persons_features (id, dominate_feature) values (1,'Agreeableness');
insert into persons_features (id, dominate_feature) values (2,'Conscientiousness');
insert into persons_features (id, dominate_feature) values (3,'Extraversion');
insert into persons_features (id, dominate_feature) values (4,'Neuroticism');
insert into persons_features (id, dominate_feature) values (5,'Openness');
But nothing.
Could you help me?

If you execute this queries in proper order, you will get no error at all. The proper order in this case should be:
CREATE TABLE persons_features
CREATE TABLE person_basic_info
insert into persons_features
insert into person_basic_info
In this case, this isn't many to many relationship, unless person can have more than one value of cambridge_analytica_psychographics_id. If so, you should create intersection table instead of reference to persons_features table.

Related

How to write stored procedure in this case?

Database: training
Task: write a stored procedure for transferring a student from one group to another, while checking whether both groups have the same number of disciplines. This is, for example, in one group the number of students was 28, and in the other 20. So that after the procedure, the number was 27 and 21. The code for creating the database tables:...
CREATE DATABASE education
GO
USE education
CREATE TABLE control_type
(
control_type_id INT IDENTITY(1,1) PRIMARY KEY,
control_type_name VARCHAR(20) NOT NULL
);
CREATE TABLE category
(
category_id INT IDENTITY(1,1) PRIMARY KEY,
category_name VARCHAR(20) NOT NULL
);
CREATE TABLE subjects
(
subject_id INT IDENTITY(1,1) PRIMARY KEY,
subject_name VARCHAR(20) NOT NULL,
count_hours INT NOT NULL,
category_id INT NOT NULL
REFERENCES category (category_id)
ON DELETE CASCADE
);
CREATE TABLE groups
(
group_id INT IDENTITY(1,1) PRIMARY KEY,
group_name VARCHAR(20) NOT NULL,
course INT NOT NULL DEFAULT '1',
count_students INT NOT NULL,
count_hours INT NOT NULL
);
CREATE TABLE [session]
(
session_id INT IDENTITY(1,1) PRIMARY KEY,
name_last_prof VARCHAR(20) NOT NULL,
name_1st_prof VARCHAR(20) NOT NULL,
name_2nd_prof VARCHAR(20) NOT NULL,
session_date DATE NOT NULL,
control_type_id INT NOT NULL
REFERENCES control_type (control_type_id)
ON DELETE CASCADE,
group_id INT NOT NULL
REFERENCES groups (group_id)
ON DELETE CASCADE,
subject_id INT NOT NULL
REFERENCES subjects (subject_id)
ON DELETE CASCADE
);
CREATE INDEX idx_group ON groups (count_students);
CREATE INDEX idx_session ON [session] (name_last_prof);
CREATE INDEX idx_subject ON subjects (count_hours);
CREATE INDEX idx_category ON category (category_name);
CREATE INDEX idx_control_type ON control_type (control_type_name);
SET dateformat dmy;
INSERT INTO category VALUES ('�����������');
INSERT INTO category VALUES ('����*������');
INSERT INTO category VALUES ('�����������');
INSERT INTO category VALUES ('��������-���������');
INSERT INTO category VALUES ('���������');
INSERT INTO category VALUES ('��������');
INSERT INTO category VALUES ('������');
INSERT INTO category VALUES ('�������');
INSERT INTO category VALUES ('��������');
INSERT INTO category VALUES ('������');
INSERT INTO control_type VALUES ('����');
INSERT INTO control_type VALUES ('�����');
INSERT INTO subjects VALUES ('��������� ����',80,1);
INSERT INTO subjects VALUES ('��������� ��',75,1);
INSERT INTO subjects VALUES ('������ �������',90,3);
INSERT INTO subjects VALUES ('��������� ����������',100,3);
INSERT INTO subjects VALUES ('������������ �����',120,3);
INSERT INTO subjects VALUES ('���������',110,6);
INSERT INTO subjects VALUES ('��������',100,6);
INSERT INTO subjects VALUES ('�����������',120,6);
INSERT INTO subjects VALUES ('��������',80,6);
INSERT INTO subjects VALUES ('������',100,7);
INSERT INTO subjects VALUES ('������ ������',80,5);
INSERT INTO groups VALUES ('���-01-1',1,20,500);
INSERT INTO groups VALUES ('���-01-2',1,25,520);
INSERT INTO groups VALUES ('ϲ-171',3,23,550);
INSERT INTO groups VALUES ('ϲ-172',3,22,540);
INSERT INTO groups VALUES ('ʲ-181',2,30,490);
INSERT INTO groups VALUES ('ʲ-182',2,29,500);
INSERT INTO groups VALUES ('��-161',4,28,480);
INSERT INTO groups VALUES ('��-162',4,24,510);
INSERT INTO groups VALUES ('��-171',3,26,500);
INSERT INTO groups VALUES ('��-172',3,23,520);
INSERT INTO [session] VALUES ('�����','���','�������','22.06.2022',1,1,3);
INSERT INTO [session] VALUES ('����','����','�������','17.01.22',2,1,4);
INSERT INTO [session] VALUES ('������','³����','�������������','20.06.2022',2,2,3);
INSERT INTO [session] VALUES ('��������','���������','�������������','15.06.2022',2,2,2);
INSERT INTO [session] VALUES ('�����','�����','�������','20.01.22',1,5,8);
INSERT INTO [session] VALUES ('������','���������','����������','18.06.2022',2,6,7);
INSERT INTO [session] VALUES ('�����','�����','³��������','23.01.22',2,3,6);
INSERT INTO [session] VALUES ('�����������','������','��������','16.01.22',2,1,10);
INSERT INTO [session] VALUES ('������','������','����������','13.06.2022',1,2,2);
INSERT INTO [session] VALUES ('������','�����','��������','15.01.22',2,2,4);
I don't understand the logic of writing SQL queries in this case...

Getting duplicate data when using the select statements

I'm getting duplicate data when trying to use the select statements, I have 9 rooms but I'm getting around 50-70 rooms when trying to display them. Help please?
I'm trying to insert data and display it using the select statement.
create table gym (
GymName VARCHAR(200) primary key,
openTime time not null,
closeTime time not null,
Price decimal not null,
);
create table Spa (
spaName VARCHAR(200) primary key,
openTime time not null,
closeTime time not null,
Price decimal not null,
);
create table customer (
CustomerID int primary key,
Firstname varchar(200) not null,
LastName varchar(200) not null,
DOB date not null check (DATEDIFF(year,DOB,getdate ()) > 18) ,
Gender char(4) not null check(Gender ='M' or Gender = 'F'),
Address varchar(200) not null default 'Jordan',
spaName VARCHAR(200) foreign key references Spa(spaName),
GymName VARCHAR(200) foreign key references gym(GymName),
);
Create table CustomerPhoNo (
CustomerID int foreign key references customer(CustomerID),
PhoneNo bigint not null,
);
create table Room (
roomNo int primary key,
Availability char(4) not null,
NoOfBeds int not null,
Rate int not null,
CheckIn date,
CheckOut date,
Price Decimal not null,
Breakfast char(4),
CustomerID int foreign key references customer(CustomerID),
);
create table LocationOfRoom (
roomNo int foreign key references Room(roomNo),
seaview char(4),
Location varchar(20) not null,
);
create table RoomType (
roomNo int foreign key references Room(roomNo),
familyRoom char(4),
doubleRoom char(4),
singleRoom char(4),
);
create table Gservice (
GymName VARCHAR(200) foreign key references gym(GymName),
Service VARCHAR(500) not null,
MachineType VARCHAR(500) not null,
);
create table PaymentCard (
CardID int primary key,
issueDate date not null,
Expirydate date not null,
CustomerID int foreign key references customer(CustomerID),
);
insert into customer values (325,'Mohammad','Alasharan','06-04-1984','M','Amman', 'BeautySpa', 'StrongBody')
insert into customer values (348,'John','Shelby','10-18-1998','M','Birmingham', 'LushLife', 'SilverGym')
insert into customer values (495,'Thomas','Hoffman','04-26-1968','M','Johannesburg', 'RelaxationTherapy', 'SilverGym')
insert into customer values (194,'Anne','Frank','07-22-2001','F','Frankfurt', 'BeautySpa', 'StrongBody')
insert into customer values (628,'Katie','Swan','02-10-1997','F','New South Wales', 'LushLife', 'FitnessHeroes')
insert into customer values (246,'Mahmoud','Alkutaifan','04-21-1994','M','Amman', 'BeautySpa', 'FitnessHeroes')
insert into customer values (864,'Karl-Heinz','Rummenigge','09-25-1955','M','Lippstadt', 'RelaxationTherapy', 'FitnessHeroes')
insert into customer values (824,'Dennis','Law','09-21-1979','M','london', 'RelaxationTherapy', 'FitnessHeroes')
insert into customer values (463,'Carles','Puyol','06-17-1973','M','madrid', 'LushLife', 'FitnessHeroes')
insert into Room values (124,'yes','1','4',null,null,'30','yes',null)
insert into Room values (135,'no','2','5','05-06-2022','05-09-2022','55','yes',495)
insert into Room values (121,'yes','1','3',null,null,'40','yes',null)
insert into Room values (139,'no','3','4','05-10-2022','05-14-2022','110','no',194)
insert into Room values (131,'no','3','3','05-18-2022','05-22-2022','130','yes',348)
insert into Room values (136,'no','4','4','04-14-2022','04-24-2022','120','yes',194)
insert into Room values (179,'yes','4','5',null,null,'95','no',null)
insert into Room values (138,'no','3','3','04-02-2022','04-06-2022','75','no',246)
insert into Room values (146,'no','3','5','05-10-2022','05-14-2022','80','yes',864)
insert into LocationOfRoom values (124,'no','south')
insert into LocationOfRoom values (135,'yes','north')
insert into LocationOfRoom values (121,'yes','south')
insert into LocationOfRoom values (139,'no','north')
insert into LocationOfRoom values (131,'no','East')
insert into LocationOfRoom values (136,'yes','west')
insert into LocationOfRoom values (179,'no','south')
insert into LocationOfRoom values (138,'no','west')
insert into LocationOfRoom values (146,'yes','north')
insert into RoomType values (124,'no','no','yes')
insert into RoomType values (135,'no','yes','no')
insert into RoomType values (121,'yes','no','no')
insert into RoomType values (139,'no','no','yes')
insert into RoomType values (131,'no','no','yes')
insert into RoomType values (136,'no','no','yes')
insert into RoomType values (179,'no','no','yes')
insert into RoomType values (138,'no','yes','no')
insert into RoomType values (146,'no','no','yes')
-- display Total number of customers who booked a single room with sea view option
select count(Firstname)
from LocationOfRoom, customer, RoomType, Room
where seaview='yes' and singleRoom='yes'
Any help would be greatly appreciated, thank you in advance!
Your FROM clause is missing the join condition for each table. In other words you are getting the cartesian product (every combination of rows) of the tables. Even distinct won't help (it will get the wrong answer). Use join conditions to link the keys of each table to each other. I'll leave this an exercise for you to try out, but this should be enough information to help you out.
I believe the solution for your problem is that you need to use DISTINCT:
SELECT COUNT(DISTINCT(Firstname))
FROM LocationOfRoom, customer, RoomType, Room
WHERE seaview='yes' AND singleRoom='yes'
I have tested it and it retrieves 9 Rooms.

Violation of PRIMARY KEY constraint 'PK__Transact__'. Cannot insert duplicate key in object 'dbo.Transactions_ID'. The duplicate key value is (1001)

When I am trying to insert execute the table and I am getting that error. And when I try to insert more rows into Employee_in I get an error
The number of columns for each row in a table value constructor must be the same
CREATE DATABASE EmployeeDatabase
USE EmployeeDatabase
CREATE TABLE Employee_In
(
EmployeeID INT NOT NULL PRIMARY KEY,
EmployeeName CHAR(30) NOT NULL,
EmployeeCountry CHAR(30)NOT NULL,
EmployeeSalary INT NOT NULL
)
USE EmployeeDatabase
GO
INSERT INTO Employee_In (EmployeeID, EmployeeName, EmployeeCountry, EmployeeSalary)
VALUES (1001, 'Sundar', 'USA', 125000),
(1002, 'Satya', 'CANADA', 120000);
SELECT * FROM Employee_In
CREATE TABLE Transactions_ID
(
TransactionID INT NOT NULL PRIMARY KEY,
EmployeeID INT FOREIGN KEY REFERENCES Employee_In(EmployeeID),
PostalDate VARCHAR(20) NOT NULL,
Amount VARCHAR(40) NOT NULL,
Description CHAR(25),
);
USE EmployeeDatabase
GO
INSERT INTO Transactions_ID (TransactionID, EmployeeID, PostalDate, Amount)
VALUES ('1001','1001','2020-04-07','20000')
Violation of PRIMARY KEY constraint 'PK__Transact__'. Cannot insert duplicate key in object 'dbo.Transactions_ID'. The duplicate key value is (1001)
This means you already have a value 1001 for the PK TransactionID in your table, most likely from and earlier insert.
INSERT INTO Transactions_ID (TransactionID, EmployeeID, PostalDate, Amount)
VALUES ('1001', '1001', '2020-04-07', '20000')
Here you are trying to insert string in columns with a datatype int... this should be:
INSERT INTO Transactions_ID (TransactionID, EmployeeID, PostalDate, Amount)
VALUES (1001, 1001, '2020-04-07', '20000')
Good luck!

SQL: "foreign key constraint fails" error message

I get an error when attempting to insert data into the songs table. I'm not sure why.
Any help would be greatly appreciated. Thanks. This is me adding details so it will let me post haha.
create table artist
(
id int primary key auto_increment,
name varchar(128) not null,
nationality varchar(128)
) ENGINE=InnoDB;
insert into artist (name, nationality) values ('Metallica', 'American');
insert into artist (name, nationality) values ('Rush', 'Canadian');
create table album
(
id int primary key auto_increment,
name varchar (128) not null,
artist int not null,
foreign key (artist) references artist(id),
genre int,
foreign key (genre) references genre(id)
) ENGINE=InnoDB;
insert into album (name, artist, genre) values ('Ride the Lightning', 1, 1);
insert into album (name, artist, genre) values ('Moving Pictures', 2, 2);
create table song
(
id int primary key auto_increment,
name varchar (128) not null,
duration varchar (128),
album int not null,
foreign key (album) references album(id)
) ENGINE=InnoDB;
insert into song (name, duration, album) values ('Fade to Black', '1 min', 1);
insert into song (name, duration, album) values ('Tom Sawyer', '2 min', 2);
create table genre
(
id int primary key auto_increment,
name varchar (128) not null,
description varchar (256)
) ENGINE=InnoDB;
insert into genre (name, description) values ('Rock', 'Lots of drums and guitars');
insert into genre (name, description) values ('Metal', 'Drums and guitars on steroids');
The order of your code is causing the problem. You need to move the
create table genre
(
id int primary key auto_increment,
name varchar (128) not null,
description varchar (256)
) ENGINE=InnoDB;
insert into genre (name, description) values ('Rock', 'Lots of drums and guitars');
insert into genre (name, description) values ('Metal', 'Drums and guitars on steroids');
Up above the "Create table album"
Here is the correct way to do it: HOW TO DO IT
This is some reasons why it did not work:
There is no table "genre" when you try to create table album:
create table album
(
id int primary key auto_increment,
name varchar (128) not null,
artist int not null,
foreign key (artist) references artist(id),
genre int,
foreign key (genre) references genre(id)
) ENGINE=InnoDB;
Here is the DEMO
Also, when you create table "genre" on time, there is another problem. You have to insert data in table "genre" to be able to insert other data.
Here is the DEMO where all works.
One is the order of the create and insert statements shouldve given you error already as table referres doesnt exists etc.
Assuming if the order is rightly implemented, as per the above error not able to insert data in songs is likely because
Your album table has a null id or id which you are inserting in songs doesnt exists in album first insert the data in album table then insert into songs table as the foreign key of songs table is checking the album table for id data

Foreign Key Not Populating with Primary Key Values

I have searched for an answer but am not finding it. I have 2 tables. Both have an auto-generated PK. The PK from table 2 is an FK in table 1. Since they are both auto-generated I assumed the FK in table 1 would populate with the value that is auto-generated from table 2 but it is not working. The FK in table 1 ends up null. Here is my SQL code for creating table 1:
CREATE TABLE Employee_tbl (
EmployeeID int PRIMARY KEY IDENTITY,
LastName varchar(20) not null,
FirstName varchar(20) not null,
Age varchar(3) not null,
JobID int FOREIGN KEY REFERENCES JobTitle_tbl(JobID),
)
and here is table 2:
create table JobTitle_tbl(
JobID int PRIMARY KEY IDENTITY,
EEO1Classification varchar(50) not null,
Exempt_nonexempt_status varchar(20) not null,
)
I also have some insert statements:
INSERT INTO Employee_tbl
(LastName, FirstName, Age)
Values
('Smith', 'John', '50'),
...
and:
INSERT into JobTitle_tbl (EEO1Classification, Job_title, )
VALUES ('Office/Clerical', 'Accounting Clerk', ),
Why is the FK value showing null when I query table 1?
The foreign keys will not auto-populate, as it doesn't know what foreign key to use. You need to either insert the rows into the JobTitle_tbl table, then select the IDs back out (or use ##identity if using sql server)
select id from JobTitle_tbl where Job_title = ''
Another option would be to update your insert statements to include the primary key, although you'll have to allow identity inserts first.
SET IDENTITY_INSERT JobTitle_tbl ON
into the JobTitle_tbl (id, title) values (1, 'Manager')
SET IDENTITY_INSERT JobTitle_tbl OFF
In either case, you'll need to then update your first insert statements with the ID that you have.
insert into Employee_tbl (LastName, FirstName, JobID) values ('Smith', 'John', 1)