SQL Statement querying same table 2 times - sql

Ok, I've got brain cells melting at an alarming rate on this SQL statement. Not my database, but I've been tasked with extracting data. So here's what I'm dealing with...
It is medical data. We have a database where ALL of the people are listed in one table- patients, as well as doctors. Each person has a unique PersonID. Let's just start with the Person table:
Person:
PersonID, PersonType, LastName, FirstName
I have another table that is hospital admissions.
Admissions:
AdmissionID, PersonID and PrimaryMD
where the Primary MD is the same as the Person ID for a doctor.
I need to extract each Admission, with the last name, and then the first name of the patient, but then I need to go back, based on the PrimaryMD identifier and use that value to pull the last name and first name of the doctor so that my results look like:
Admission | PatientLastName | PatientFirstName | DoctorLastName | DoctorFirstName
Ultimately, I'll need to pull address information for both the patient, and the doctor which is all stored in an address table with the same PersonID as in the person table, and then pull the doctor's address using the primarymd against the person table. But I can't figure how to write two queries in the same statement against these similar columns. I tried using aliases, and some left and inner joins and even a union, but I can't seem to get things right.
Any assistance would be hugely appreciated.

Try this:
SELECT
a.AdmissionID,
pat.LastName AS PatientLastName,
pat.FirstName AS PatientFirstName,
doc.LastName AS DoctorLastName,
doc.FirstName AS DoctorFirstName
FROM Admissions a
INNER JOIN Person pat
ON a.PersonID = pat.PersonID
INNER JOIN Person doc
ON a.PrimaryMD = doc.PersonID
For getting addresses use the same steps:
SELECT
a.AdmissionID,
pat.LastName AS PatientLastName,
pat.FirstName AS PatientFirstName,
doc.LastName AS DoctorLastName,
doc.FirstName AS DoctorFirstName
FROM Admissions a
INNER JOIN Person pat
ON a.PersonID = pat.PersonID
INNER JOIN Person doc
ON a.PrimaryMD = doc.PersonID
INNER JOIN Addresses addPat
ON pat.PersonID = addPat.PersonID
INNER JOIN Addresses addDoc
ON doc.PersonID = addDoc.PersonID

Related

Trying to figure out a sql query to fetch the right data from multiple tables

So I have a database and I have 4 tables (admin, appointment, doctor, patient).
I only care about appointment, doctor and patient.
Diagram of these 3 tables:
What I want is based on a patients amka(int) to find all his appointments and show his name, surname and doctors name, surname.
I made this query:
(SELECT doctor.name, doctor.surname
FROM public.doctor
INNER JOIN public.appointment ON doctor.username = 'alouisot2')
union
(SELECT patient.name, patient.surname
FROM public.patient
INNER JOIN public.appointment ON patient.amka = '713783001');
The problem with this query is that it will only show appointments between this specific doctor and I just want to get all the doctors names and surnames.
Also I use postgresql.
I was trying to figure it out but I couldn't. I need to restructure the query but I cannot think how I would solve this problem.
If you have any idea on how to do achieve this I would really appreciate it.
Try this - properly join the three tables together (doctor to appointment based on the common username column, appointment to patient on the common amka column), and define the WHERE clause with your desired values:
SELECT
doctor.name, doctor.surname,
patient.name, patient.surname
FROM
public.doctor
INNER JOIN
public.appointment ON doctor.username = appointment.username
INNER JOIN
public.patient ON appointment.amka = patient.amka
WHERE
doctor.username = 'alouisot2'
AND patient.amka = '713783001';
this query just needs simple joins; you seem to have overcomplicated it a lot for some reason...
SELECT
patient.name,
patient.surname,
doctor.name,
doctor.surname
FROM public.patient
INNER JOIN public.appointment
ON patient.amka = appointment.amka
INNER JOIN public.doctor
ON appointment.username = doctor.username
WHERE patient.amka = '713783001'

Complex SQL Query with Dead Ends and 7 Tables

I was tasked with creating a complex query that incudes all of the data from all of the tables minus the Keys. I am having an issue with the dead end tables and how to circle back around to include the data of the connecting table. I need to select columns DivisionName, ProgramName, ProgramChairFName, ProgramChairLName, CourseID, OutcomeDescription from the listed tables.
SQL Diagram
The 'dead-ends' aren't really dead-ends. When you join all the tables by the appropriate keys, you'll get an assembly of the information you want.
Consider a really simple example:
table person
id name
1 Alice
table pet
id person_id animal
1 1 cat
table hobby
id person_id activity
1 1 dancing
Here, the two tables pet and hobby link to the person table via the person_id key.
In your thinking, "pet" could be considered a "dead-end" because it doesn't link to hobby. But it doesn't need to. The query:
SELECT name, animal, activity
FROM person
JOIN pet ON person.id = pet.person_id
JOIN hobby ON person.id = hobby.person_id;
creates the correct joins back to the person table. It's not a linear path (person -> pet -> hobby). The nature of the joins are specified by the "ON" part of the query. You can see this simple example works here: http://sqlfiddle.com/#!9/02c94b/1
So, in your case, you can have a series of JOINs:
SELECT [all the columns you want]
FROM Division d JOIN Program p
ON d.DivisionKey = p.DivisionKey
JOIN ProgramChairMap pcm
ON p.ProgramKey = pcm.ProgramKey
JOIN ProgramChair pc
ON pcm.ProgramChairKey = pc.ProgramChairKey
JOIN Course c
ON p.ProgramKey = c.ProgramKey
JOIN CourseOutcome co
ON c.CourseKey = co.CourseKey
JOIN Outcome o
ON co.OutsomeKey = o.OutcomeKey

How to query in a way that relates a name to an ID and then using that ID to sum up what comes under that ID

I'm a student learning SQL. With querying, if you are given data that you have to relate to a primary key in the same table that will then be used to identify data in another table, how do you query that? I only want a push in the right direction because I don't want to copy and paste someone's code.
For example:
You are to find out how many staff are being managed by a manager and you are to find this by using the managers first and last name (which is not the primary key). The database is below. ManagerNo and StaffID are the same.
Branch (BranchNo, ManagerNo)
Staff (staffID, fName, lName, position, BranchNo)
Thank you for your time
You would use two joins:
select s.*
from staff s join
branch b
on s.BranchNo = b.BranchNo join
staff sm
on sm.staffId = b.ManagerNo
where sm.fname = ? and sm.lname = ?;

How to link tables correctly in SQL to add roles to staff?

Currently I have a staff table with columns:
Staff_Id, first_name, Surname.
My second table is:
Id, management_role.
When I link the tables each staff member gets added to every management role. So for example a person in first table called Jim is added three times as manager, supervisor, intern and this happens for every staff.
Some things to consider that are your ID columns are primary keys for their respective tables. If not are every value in the column is unique? Also are ids not
From your description you might be using a cross join here. The thing you need is inner join so it joins the matching id's together.
So you can do
SELECT *
FROM staff_table as st
INNER JOIN management_table as mt
ON st.Staff_Id = mt.ID

MySQL multi table join query

Result needed: The registration number of the cars used by Instructors at the Glasgow, Bearsden office.
The 3 relevant tables I have are; ( I have omitted the non-relevant table information, to simplify this. The database is called easydrive.
No this is not a School or UNI assignment, it is a question from a text book, that we have been given to do so we can learn how to do it, no marks are awarded for this, so you are not doing my homework for me.
**++Staff++**
(PK) Staff ID
(FK) Address ID
(FK) Office
(FK) Car Allocation Number
First Name
Last Name
Position/Title
Office
**++CarAllocation++**
(PK) Car Allocation Number
(FK) Staff ID
(FK) Car ID
**++Car++**
(PK) Car ID
Car Rego
So I need to so a join I think and I think it needs to go something along these lines but am very confused.
SELECT car.rego
FROM car
WHERE staff.office=’Glasgow’ OR ‘Bearsden’
Can someone please fill in the blanks so I can learn how to perform this, do I need to make a new table?
You query most probably needs to look something like this:
SELECT first_name, last_name, car_rego
FROM staff
JOIN carallocation ON (carallocation.staff_id = staff.staff_id)
JOIN car ON (car.car_id = carallocation.car_id)
WHERE staff.office = 'Glasgow' OR staff.office = 'Bearsden';
Note that JOIN is a synonym for an INNER JOIN in MySQL.
I haven't tested it but this should help.
select car.rego
from car
inner join carrallocation ca on ca.carid = car.carid
inner join staff s on ca.staffid = s.staffid
where s.office in ('Glasgow', 'Bearsden')
What you are missing is the joins between the tables. You need to join to the intermediary table to get the relationship between the staff and car tables.
As far as car_allocation is an intermediate table, it's rather better to put it into the FROM clause and JOIN others:
SELECT car.rego
FROM car_allocation A
JOIN car ON A.car_id = car.car_id
JOIN stuff ON A.stuff_id = stuff.stuff_id
AND (staff.office = 'Glasgow' OR staff.office = 'Bearsden' -- OR some another condition, etc)
Pay attention to brackets, they groups conditions.
or
SELECT car.rego
FROM car_allocation A
JOIN car ON A.car_id = car.car_id
JOIN stuff ON A.stuff_id = stuff.stuff_ids
AND staff.office IN ('Glasgow', 'Bearsden')
If you have an enumeration you can use IN operator.
Also JOIN means the same as INNER JOIN. Here's MySQL manual considering JOIN syntax