I am having a major problem joining 5 tables because each table only has 1 column in common with only 1 other table.
Here are my tables and columns in each table:
TABLE (COLUMNS)
person (person_id, first_name, last name)
building (building_id, building_name)
room (room_id, room_number, building_id, capacity)
meeting (meeting_id, room_id, meeting_start, meeting_end)
person_meeting (person_id, meeting_id)
OK, now here is what I am trying to do (pasted from a homework assignment):
Construct the SQL statement to find all the meetings that person_id #1 has to attend. Display the following columns:
Person’s first name
Person’s last name
Building name
Room number
Meeting start date and time
Meeting end date and time
Now I know how to join 2 tables but I have no idea how to pull info from 5 different tables like this.
I tried looking up how to do this and it just says to do a UNION command, and I am just learning and have yet to cover that.
As UNION is used to combine the result from multiple SELECT statements into a single result set, you don't need it for this scenario. You have to join all the tables one by one based on their Id.
SELECT P.First_Name, P.Last_Name, B.Building_name, R.Room_Number,
M.Meeting_Start, M.Meeting_End FROM Person P
JOIN Person_Meeting PM ON P.Person_Id = PM.Person_Id
JOIN Meeting M ON PM.Meeting_Id = M.Meeting_Id
JOIN Room R ON M.Room_Id = R.Room_Id
JOIN Building B ON R.Building_Id = B.Building_Id
WHERE P.Person_Id = 1
Related
Okay so this is my best attempt at making a query. It currently executes but returns nothing the other attempts have not worked.
The joins are wrong I believe and I'm not sure how to fix them or do this right
In this query I am trying to get the activity details with staff assigned to those activities matching all conditions below.
The staff and activities are linked in the Allocation table with a Staff ID assigned to an Activity ID there.
--Teach at least 2 modules during 2019 in a certain campus
The staffID must occur at least twice in the Teach table at the field StaffID
The spaID 5 or 6 would correspond to the campus so teach two modules at this time and ID.
--Supervise more than 1 colleagues
This is in the staff table with SupervisorID being a foreign key of StaffID in the same table.
So the Staff ID allocated to the activity needs to supervise more than one colleague with their ID appearing in SupervisorID more than once.
--The related activity is internal one
The activity is internal if it equals to 1.
So to sum it up the activity details should only appear in the query results if it has staff matching all the conditions above
SELECT Activity.AcID, Activity.Title, Activity.CaID, Activity.Internal, Activity.BuID, Budget.Amount FROM Activity
INNER JOIN Budget ON Activity.AcID = Budget.BuID
INNER JOIN Allocation ON Activity.AcID = Allocation.AcID
INNER JOIN Staff ON Allocation.StaffID = Staff.StaffID
INNER JOIN Teach ON Allocation.StaffID = Teach.StaffID
WHERE Activity.Internal=1 AND
Allocation.StaffID IN (
SELECT Staff.SupervisorID
FROM Staff
GROUP BY StaffID
HAVING COUNT(Staff.SupervisorID=Allocation.StaffID) >1)
AND Allocation.StaffID IN (
SELECT Teach.StaffID
FROM Teach
WHERE Teach.Year='2019' AND Teach.SpaID=5 OR 6
GROUP BY Teach.StaffID
HAVING COUNT(Allocation.StaffID=Teach.StaffID) >=2);
Table details are below if you want to look at them for more details
Table Activity -- AcID, Title, CaID, BuID, Status, Started, Ended Internal
Table Allocation -- StaffID, AcID
Table Budget -- BuID, Amount, Approver, Payee, Status
Table Campus -- CaID, Address, GmName, Country, Status
Table Classroom -- RmID, Capacity, CaID, Location, Type, Status
Table Module -- ModuleID, Module Name, DeptID, Programme, TMode, Date_of_Firstoffer
Table SpaceAssign -- SpaID, RmID, TID, Manager, Approved
Table Staff -- StaffID, Title, FirstName, LastName, DeptID, CaID, Joined, LeftD, Current, Salary, ContractType, SupervisorID
Table Teach -- TID, ModuleID, StaffID, SpaID, Semester, Year
I have tried my best to explain this well sorry for any confusion.
Without data It's very tough to find a solution. Please try this:
SELECT Activity.AcID, Activity.Title, Activity.CaID, Activity.Internal, Activity.BuID, Budget.Amount FROM Activity
INNER JOIN Budget ON Activity.AcID = Budget.BuID
INNER JOIN Allocation ON Activity.AcID = Allocation.AcID
INNER JOIN Staff ON Allocation.StaffID = Staff.StaffID
INNER JOIN Teach ON Allocation.StaffID = Teach.StaffID
WHERE Activity.Internal=1 AND
Allocation.StaffID IN (
SELECT Staff.SupervisorID
FROM Staff
GROUP BY SupervisorID
HAVING COUNT(*) >1)
AND Allocation.StaffID IN (
SELECT Teach.StaffID
FROM Teach
WHERE Teach.Year='2019' AND Teach.SpaID=5 OR 6
GROUP BY Teach.StaffID
HAVING COUNT(*) >=2);
It is hard to tell without having access to the data but you can try to change the inner joins to left joins and also:
This
WHERE Teach.Year='2019' AND Teach.SpaID=5 OR 6
Should be
WHERE Teach.Year='2019' AND (Teach.SpaID=5 OR Teach.SpaID=6)
This looks incorrect as well:
INNER JOIN Budget ON Activity.AcID = Budget.BuID
Should be:
INNER JOIN Budget ON Activity.BuID = Budget.BuID
SOLVED-run UPDATE building SET building_name = "Main Street Building" WHERE building_id = 2;
From there, the task 3 query will return proper results.
Task One:
Query:
SELECT first_name, last_name, building_name, room.room_id, meeting_start,meeting_end
FROM meeting, person, person_meeting,room, building
WHERE room.room_id=meeting.room_id
AND meeting.meeting_id=person_meeting.meeting_id
AND person.person_id=person_meeting.person_id
AND room.building_id=building.building_id
AND person.first_name='Tom'
AND person.last_name='Hanks';
Task Two:
Query:
SELECT first_name, last_name, building_name, room.room_id, meeting_start,meeting_end
FROM meeting, person, person_meeting,room, building
WHERE room.room_id=meeting.room_id
AND meeting.meeting_id=person_meeting.meeting_id
AND person.person_id=person_meeting.person_id
AND room.building_id=building.building_id
AND meeting.meeting_id=2;
Task Three:
Query:
SELECT first_name, last_name, building_name, room.room_id,meeting.meeting_id, meeting_start, meeting_end
FROM meeting, person, person_meeting,room, building
WHERE room.room_id=meeting.room_id
AND meeting.meeting_id=person_meeting.meeting_id
AND person.person_id=person_meeting.person_id
AND room.building_id=building.building_id
AND building_name='Main Street Building';
Task Four:
Query:
SELECT count(person_id) 'Count of meeting attendees', meeting.meeting_id,meeting_start,meeting_end
FROM meeting, person_meeting
WHERE meeting.meeting_id=person_meeting.meeting_id
GROUP BY meeting.meeting_id;
Task Five:
Query:
SELECT first_name, last_name, meeting.meeting_id, meeting_start, meeting_end
FROM meeting INNER JOIN person_meeting ON meeting.meeting_id=person_meeting.meeting_id
INNER JOIN person ON person.person_id=person_meeting.person_id
AND meeting_start<'2016-12-25 12.00.00';
Task 1,2,4,5 and 5 all run perfectly. if you all need the task prompts, let me know.
Note: I haven't test this yet.
I changed the queries based on our recent interaction.
This is your original
SELECT first_name, last_name, building_name, room.room_id,meeting.meeting_id, meeting_start, meeting_end
FROM meeting, person, person_meeting,room, building
WHERE room.room_id=meeting.room_id
AND meeting.meeting_id=person_meeting.meeting_id
AND person.person_id=person_meeting.person_id
AND room.building_id=building.building_id
AND building_name='Main Street Building';
This is the way I would try to build it
Based on page 2 and 3 in the document, you provided, https://snhu.brightspace.com/d2l/lor/viewer/viewFile.d2lfile/76437/9523,2/, I would do the following:
First, I would obtain information about the building.
SELECT building_id
FROM building
WHERE building_name like '%Main Street Building%';
Note: I am assuming that the building name is correct. However, just in case, I am using the wildcard % before and after the name
Next, I would obtain the information about the room:
SELECT b.building_name, r.room_id
FROM room r
LEFT JOIN building b
ON r.building_id = b.building_id
WHERE b.building_name like '%Main Street Building%';
Following that, I would obtain the information about the meeting:
SELECT b.building_name, r.room_id, m.meeting_id, m.meeting_start, m.meeting_end
FROM room r
LEFT JOIN building b
ON r.building_id = b.building_id
LEFT JOIN meeting m
ON r.room_id = m.room_id
WHERE b.building_name like '%Main Street Building%';
Finally, I would obtain the information of the IDs of people that will be in that meeting and show their names:
SELECT b.building_name, r.room_id, m.meeting_id, m.meeting_start, m.meeting_end, p.first_name, p.last_name
FROM room r
LEFT JOIN building b
ON r.building_id = b.building_id
LEFT JOIN meeting m
ON r.room_id = m.room_id
LEFT JOIN persom_meeting pm
ON m.meeting_id = pm.meeting_id
LEFT JOIN person p
ON pm.person_id = p.person_id
WHERE b.building_name like '%Main Street Building%';
If by any chance, these queries do not work, I would advice that you ensure that the relationships exists between the tables.
This means that there should be a building_id match, a room_id match, a meeting_id match and a person_id match between the tables. Plus, I would check that the building name is spelled correctly since its case-sensitive.
The reason I use LEFT JOINs is so I can display all the information of the previous tables (all the rows) plus the records in which the IDs match the foreign keys IDs. As explained here: http://www.acarlstein.com/?p=4168
Also, in http://www.acarlstein.com/?p=4194, I am showing how a Two Left (Outer)Joins would work.
However, in your case, it is more like a chain that is being build so it doesn't match the diagram but you can perhaps get the idea of what I mean.
I'm fairly new to MySQL, and trying to understand the many-to-many relationship since these examples can popup in interviews
There are 3 tables, and since a Student can have many courses and a Course can have many students, this is a Many-to-Many relationship right?
The tables are
Student- has student ID, name, date of birth, and department.
Courses- Has ID, Name of course
Student_Courses- Has student_id, course_id
How would I display these 2 questions-
1) Given a studentID, return all the names of the courses the student is taking
2) Return the name of students who is taking X amount of courses or more (Ex. 4 or more courses).
Im trying to write queries on these, but I'm stuck...
In the case of selecting all of the courses for a given student ID you could try the following, which will return one row for each Course a Student is associated with.
select
s.name as StudentName,
c.name as CourseName
from `Student` as s
inner join `Student_Course` as sc on (sc.student_id = s.ID)
inner join `Course` as c on (c.ID = sc.course_id)
where
(s.`ID` = 'given_Student_ID_here')
;
As for selecting a list of the names of Students taking N or more courses, for this you might use an aggregating sub-select as a WHERE clause in which we reference one of the outer tables (i.e. [Student]) so that the result of the aggregation is personalised per Student record:
select
s.name as StudentName
from `Student` as s
where
(
(
select count(*)
from `Student_Course` as sc
inner join `Course` as c on (c.ID = sc.course_id)
where (sc.student_id = s.ID)
) >= 4
)
;
You might also consider an alternative approach to this second problem by using the GROUP BY and HAVING clauses:
select
s.name as StudentName
from `Student` as s
inner join `Student_Course` as sc on (sc.student_id = s.ID)
inner join `Course` as c on (c.ID = sc.course_id)
group by
s.name
having
count(*) >= 4
;
Suppose that we have four tables in the following structure (Table name - fields):
person - id, name
doctor - id_person, specialty
pacient - id_person, disease
appointment - doctor_id, pacient_id, date
How can I construct a query to return the doctor's name and specialty, the pacient's name and disease and the appointment date?
Here's where I've got so far:
SELECT person.name, doctor.specialty, pacient.disease, appointment.date
FROM appointment
INNER JOIN person
ON appointment.pacient_id=person.id
INNER JOIN doctor
ON appointment.doctor_id=doctor.id_person
INNER JOIN pacient
ON appointment.pacient_id=pacient.id_person
But this is not returning the right fields. I think the problem resides in returning the same field (person.name) for two different ids (doctor and pacient) in the same row.
You need to do two separate joins to the person table, and use aliases to identify the individual tables like so:
select
dp.name as DoctorName
, doctor.specialty
, pp.name as PacientName
, pacient.disease
, appointment.date
from appointment
inner join doctor
on appointment.doctor_id = doctor.id_person
inner join person dp
on appointment.doctor_id = dp.id
inner join pacient
on appointment.pacient_id = pacient.id_person
inner join person pp
on appointment.pacient_id = pp.id
i have gotten the task of creating a statistic from tables that look like this:
Faculty
1 FacultyName1
2 FacultyName2
3 FacultyName3
4 FacultyName4
5 FacultyName5
and this:
Student
1 StudentName1 FacultyNr2
2 StudentName2 FacultyNr3
3 StudentName3 FacultyNr5
4 StudentName4 FacultyNr2
now i have to create a statistic which Groups the Faculties into newly created fields and groups by them.
Say:
Faculty Group 1 Count: 3
Faculty Group 2 Count: 1
for this example lets say that all those of FacultyName1,FacultyName2,FacultyName3 should be listet as of "Faculty Group 1" and FacultyName4 and FacultyName5 as of "Faculty Group 2".
I started by doing the following:
Select Count(*)
FROM Student INNER JOIN Faculty on Student.FacultyID = Faculty.ID
But am stuck trying to understand how to Group, how i could create Groups in the Code, where i could just say: Group by FacultyGroups (Select Case When FacultyName = 'FacultyName1' = 'Faculty Group 1')
or something similiar, does anybody have any idea ?
Assuming that you have added a GroupID column in your Faculty table
SELECT COUNT(*), f.GroupID
FROM Student AS s
INNER JOIN Faculty AS f ON s.FacultyID = f.ID
GROUP BY f.GroupID
It gives you the number of student per group of faculties and the id of this group
There are better ways, but this should work:
SELECT
CASE
WHEN f.Name IN ('FacultyName1', 'FacultyName2', 'FacultyName3') THEN 'FacultyGroup1'
WHEN f.Name IN ('FacultyName4', 'FacultyName5') THEN 'FacultyGroup2'
END AS FacultyGroup,
COUNT(*) AS Students
FROM
Student s
INNER JOIN Faculty f ON s.FacultyID = f.ID
GROUP BY
CASE
WHEN f.Name IN ('FacultyName1', 'FacultyName2', 'FacultyName3') THEN 'FacultyGroup1'
WHEN f.Name IN ('FacultyName4', 'FacultyName5') THEN 'FacultyGroup2'
END;
If your "group" logic becomes too long then it will look messy in your query, so you might want to pre-calculate this. You could do this by using a sub-query for example, so one part of your query (the sub query) would convert faculties to groups and the other "main" part would count the students per group.