how to join two/ three tables in postgresql - sql

I am new to creating databases and want to know how to solve this problem or if I'm even doing it right.
I'm trying to join two/three tables, staff, role and staff_role together so that the staff can have more than one role and I'm not sure how to go about it any help is appreciated! , this is my code for these tables:
CREATE TABLE ROLE(
ROLE_ID SERIAL PRIMARY KEY,
ROLE_NAME VARCHAR(50) NULL);
Insert into role(role_name) values('Manager');
Insert into role(role_name) values('Glass_Fibre_Specialist');
Insert into role(role_name) values('Engine_Technician');
Insert into role(role_name) values('Electrician');
Insert into role(role_name) values('General_Technician');
CREATE TABLE STAFF(
STAFF_ID SERIAL PRIMARY KEY,
STAFF_FNAME VARCHAR(35) NOT NULL,
STAFF_LNAME VARCHAR(35) NOT NULL,
ADDR VARCHAR(100) NOT NULL,
POSTCODE VARCHAR(20) NOT NULL,
WORK_EMAIL VARCHAR(150) NOT NULL);
CREATE TABLE STAFF_ROLE(
STAFF_ID int NOT NULL REFERENCES STAFF(STAFF_ID),
ROLE_ID int NOT NULL REFERENCES ROLE(ROLE_ID));`
this is what I tried using to join my tables but I don't think it's right
SELECT
s.Staff,
r.role,
sr.Staff_role
FROM Staff s
INNER JOIN role AS r
ON r.StaffID = s.StaffID
INNER JOIN staff_role sr
ON sr.staff_roleId = r.roleId;
`
I have tried looking at how to join the tables but it has not worked/ I'm not too confident about how to do it, I have also tried adding two types of roles as well, but it kept coming up with errors and I'm kind of stuck

Related

I need to JOIN using a linking table

The three tables are as follows:
CREATE TABLE Artist
(
ArtistKey char(20) NOT NULL PRIMARY KEY,
ArtistName varchar(50) NOT NULL
)
CREATE TABLE AlbumInfo
(
AlbumInfoKey char(20) NOT NULL PRIMARY KEY,
AlbumTitle varchar(50) NOT NULL,
AlbumDate date NULL,
AlbumStudio varchar(50) NULL
)
CREATE TABLE AlbumArtist
(
AlbumInfoKey char(20) NOT NULL,
ArtistKey char(20) NOT NULL,
PRIMARY KEY CLUSTERED
(
AlbumInfoKey ASC,
ArtistKey ASC
))
My objective is to list all of the artists and their albums. I can't seem to get anything to work.
I have tried:
SELECT
Artist.ArtistName,
AlbumInfo.AlbumTitle
FROM Artist
JOIN AlbumArtist
ON Artist.ArtistKey = AlbumArtist.ArtistKey
JOIN AlbumInfo
On AlbumInfo.AlbumInfoKey = AlbumArtist.AlbumInfoKey
However this gives me back nothing not even an error.
Alright, I had to re-do your whole task, and I have come up with more professional, and better way of managing database. You need to drop those tables, and re-do whole thing like show in code below :
--First create Artist table
CREATE TABLE Artist
(
Artist_key int PRIMARY KEY IDENTITY(1,1),
ArtistName varchar(50) NOT NULL,
);
--Then create Album table
CREATE TABLE AlbumInfo
(
Album_key int NOT NULL PRIMARY KEY IDENTITY(1,1),
AlbumTitle varchar(50) NOT NULL,
AlbumDate date NULL,
AlbumStudio varchar(50) NULL,
Artist_key int FOREIGN KEY (Artist_key) REFERENCES Artist(Artist_key)
);
-- Must have Artist data before referencing in the album table
INSERT into Artist (ArtistName) values ('John')
INSERT into AlbumInfo (AlbumTitle,AlbumDate,AlbumStudio,Artist_key) values ('ABC3','2020-6-12','Def3',(select Artist_key from Artist where Artist_key = 1 ))
--test if data has been inserted
SELECT * FROM Artist
SELECT * FROM AlbumInfo
-- And finally this query will show the Artist with their relevant Albums
SELECT ArtistName,af.AlbumTitle,AlbumStudio from Artist a join AlbumInfo af on af.Artist_key = a.Artist_key
And the result is :

How do i fill my table with data from 3 different tables?

So I am working on a football world cup database. These are my important tables:
CREATE TABLE Countries(
Cid SERIAL PRIMARY KEY,
Name VARCHAR(256) NOT NULL UNIQUE
);
CREATE TABLE Stadiums(
Sid SERIAL PRIMARY KEY,
Name VARCHAR(256) NOT NULL UNIQUE,
Cid INT REFERENCES Countries NOT NULL
);
CREATE TABLE Groups(
Gid SERIAL PRIMARY KEY,
Name VARCHAR(64) NOT NULL,
TYear SMALLINT REFERENCES Tournaments NOT NULL
);
CREATE TABLE Teams(
Tid SERIAL PRIMARY KEY,
Cid INT REFERENCES Countries NOT NULL,
Gid INT REFERENCES Groups NOT NULL
);
CREATE TABLE Matches(
Mid INT PRIMARY KEY,
HomeTid INT REFERENCES Teams NOT NULL,
VisitTid INT REFERENCES Teams NOT NULL,
HomeScore SMALLINT NOT NULL,
VisitScore SMALLINT NOT NULL,
MatchDate DATE NOT NULL,
MatchType VARCHAR(64) NOT NULL,
Sid INT REFERENCES Stadiums NOT NULL
);
CREATE TABLE tempmatches(
year INTEGER,
host_country VARCHAR(255),
match_id INTEGER,
type VARCHAR(255),
date DATE,
location1 VARCHAR(255),
team1 VARCHAR(255),
team2 VARCHAR(255),
score1 INTEGER,
score2 INTEGER
);
so my current problem is that I need to populate the columns HomeTid and VisitId of the Matches table with the tid's from the team's table that corresponds with the country of that team from the countries table but I'm not sure how to do that. I tried a few queries but none of them seemed to work. Has anyone an idea on how to solve this?
Using JOIN keyword you can combine 2 tables data.
Here, in this case, you have to use 3-way join.
Eg:
3-way JOIN can be used in this way:
SELECT * FROM table1 JOIN table2 ON table1.col1=table2.col2 JOIN table3 ON table3.col3=table.col1;
Here the 2 tables will get joined based on the columns mentioned after the "ON" keyword.
Here is a reference link in which JOIN is explained clearly
https://www.w3schools.com/sql/sql_join.asp
Use JOIN operation. In SQL it helps to combine several tables(queries) in one

SQL Query: I want to display UserName and role_discription using a junction table

Hi can someone please help?
I have three tables tblUsers, tblRoles and tblUserRoles
How do I display UserName from a tblUsers table and role_discription
from tblRoles table.
CREATE TABLE tblRoles(
roleID int IDENTITY(1,1) PRIMARY KEY NOT NULL,
role_description varchar(50) NOT NULL
);
)CREATE TABLE tblUsers(
userID int IDENTITY(1,1) PRIMARY KEY,
FirstName varchar(50) NOT NULL,
LastName varchar(50) NOT NULL,
Age int NOT NULL,
UserName varchar(50) NOT NULL,
Password varchar(50) NOT NULL);
create table tblUserRoles (
userID int REFERENCES tblUsers(userID) NOT NULL,
roleID int REFERENCES tblRoles(roleID)NOT NULL,
);
alter table tblUserRoles
Add Constraint PK_UserRoles
Primary Key Clustered (userID,roleID)
I know basic SELECT statements and can show everything in tblUserRoles table but would like to show names and descriptions instead of ID numbers
Here is a query to display user_name and role_description
SELECT t1.UserName , t2.role_description from tblUsers t1 INNER JOIN tblUserRoles t3 ON t1.userID = t3.userID INNER JOIN tblRoles t2 on t3.roleID = t2.roleID
Here the 1st join will join tables tblUsers and tblUserRoles on column userID and the 2nd join will join tables tblUserRoles and tblRoles on column roleID.

Creating a view in Sql with connected tables

I am trying to create a view off of two different tables. Basically I have 2 tables
(MatchStats- Holds all of the fixture information)
(Team - Holds all of the team information)
Here is the code for both tables
Team
CREATE TABLE TEAM
(
TeamID int NOT NULL,
TeamName varchar(30) NOT NULL,
Teamlocale varchar(30) NOT NULL,
CONSTRAINT pkTeamID PRIMARY KEY (TeamID),
)
MatchStats
CREATE TABLE MATCHSTATS
(
MatchStatsID int NOT NULL,
Team1ID int NOT NULL,
Team1Goals int NOT NULL,
Team2ID int NOT NULL,
Team2Goals int NOT NULL,
RefereeID int NOT NULL,
PitchID int NOT NULL,
sessionTime varchar(20) NOT NULL,
sessionDate varchar(20) NOT NULL,
CONSTRAINT pkMatchStatsID PRIMARY KEY (MatchStatsID),
CONSTRAINT fkTeam1ID FOREIGN KEY (Team1ID) REFERENCES TEAM(TeamID),
CONSTRAINT fkTeam2ID FOREIGN KEY (Team2ID) REFERENCES TEAM(TeamID),
CONSTRAINT fkReferee FOREIGN KEY (RefereeID) REFERENCES REFEREE(RefereeID),
CONSTRAINT fkpitchID FOREIGN KEY (PitchID) REFERENCES Pitch(pitchID),
)
I am trying to create a view that will display the fixture information but use the team name instead of ID. I have been researching and looking at previous questions online and I just cant seem to understand how to do it
This is what I have managed to come up with
CREATE VIEW FIXTUREHSITORY AS
SELECT m.Team1ID, m.Team1Goals, m.Team2ID, m.Team2Goals, T.TeamName
from MATCHSTATS as m
JOIN TEAM as t ON t.TeamID on
Overall I am trying to create a report that looks like this
Team 1 Name | Goals | Team 2 Name | Goals
Sorry if I seem vague and thanks in advance
A solution to your problem:
MSSQL
CREATE VIEW FIXTUREHISTORY AS
SELECT t1.TeamName Team1Name,
m.Team1Goals Team1Goals,
t2.TeamName Team2Name,
m.Team2Goals Team2Goals
from MATCHSTATS as m
INNER JOIN TEAM as t1 ON t1.TeamID = m.Team1ID
INNER JOIN TEAM as t2 ON t2.TeamID = m.Team1ID
Demo Link:
http://sqlfiddle.com/#!18/34883/1

Calculate a value with other values

Let's make it simple:
USE Example1
CREATE TABLE Person
(PersonID int PRIMARY KEY IDENTITY(1,1),
FirstName nchar(20) NOT NULL,
LastName nchar(20) NOT NULL,
Salary money NOT NULL
)
CREATE TABLE Student
(StudentID int PRIMARY KEY IDENTITY(1,1),
FirstName nchar(20) NOT NULL,
LastName nchar(20) NOT NULL,
FatherID int NOT NULL,
MotherID int NOT NULL,
CONSTRAINT fk_Student_FatherID FOREIGN KEY (FatherID)
REFERENCES Person(PersonID),
CONSTRAINT fk_Student_MotherID FOREIGN KEY (MotherID)
REFERENCES Person(PersonID)
)
CREATE TABLE Registration
(RegistrationID int PRIMARY KEY IDENTITY(1,1),
StudentID int NOT NULL,
Date datetime NOT NULL,
MonthlyPayment ??????????
CONSTRAINT fk_Registration_StudentID FOREIGN KEY (StudentID)
REFERENCES Student(StudentID)
)
INSERT INTO Person VALUES ('John','Doe','1000')
INSERT INTO Person VALUES ('Mary','Poppins','800')
INSERT INTO Student VALUES ('Gary','Doe', 1, 2)
INSERT INTO Registration VALUES (1, getdate(),???)
I have a student that is going to make a registration in a school and have a monthly payment that is going do be FatherSalary*0.5 + MotherSalary*0.5 but I don't know how to make that happen. I'm new in SQL and maybe this is simple and I should know how to make it, but I don't and I need help.
Are you sure you need MonthlyPayment column in your table?
You can create table Registration without MonthlyPayment field and then create a view
create view vw_Registration
as
select
R.RegistrationID,
R.StudentID,
R.Date,
F.Salary * 0.5 + M.Salary * 0.5 as MonthlyPayment
from Registration as R
left outer join Student as S on S.StudentID = R.StudentID
left outer join Person as F on F.PersonID = S.FatherID
left outer join Person as M on M.PersonID = S.MotherId
SQL FIDDLE EXAMPLE
If the expression "FatherSalary*0.5 + MotherSalary*0.5" will not change, then you can use trigger i suppose.Your trigger will check the inserts to your Registration table. At the time of an insert, it will get the student id, then using this id it will get the necessary data from your student table and your Person table. At that moment, you will have access to the Money column for both father and mother. Calculate the result, and let the trigger to the insert for you.
A view sounds good at first hand, but I can imagine a scenario where you want to calculate a monthly payment based on the data available at a certain point in time so the monthly payment does not change everytime the father or mother has a change in salary...
In that case you can use this:
INSERT INTO Registration
(StudentID, Date, MonthlyPayment)
SELECT S.StudentID, getdate(), ISNULL(F.Salary, 0) * 0.5 + ISNULL(M.Salary, 0) * 0.5
FROM Student as S
left outer join Person as F on F.PersonID = S.FatherID
left outer join Person as M on M.PersonID = S.MotherId
WHERE S.StudentID = 1
SQL Fiddle