So am trying to write a MySQL query with a simple join to pull things from two different tables.
The fist table is a students table (Sorry its not prettier I couldn’t find a better way to put them in)
id first_name last_name major phone_number
-------------------------------------------------
1 Eric Larsen CS 1234567891
2 Sam Coons English 1234567891
3 David Brown MAE 1234567891
4 Richard Brown CS 1234567891
5 Kendra Griffiths FCHD 1234567891
The second is a scores table, rich now it just has one row,
id student_id item_id score
------------------------------
1 1 1 20
There is a third table with a list of items but is not really needed for this particular query.
I want to pull all of the students along with there score for scores.item_id = 1 if they have a score, if they don’t I still want it to pull the information for the student, well, there name at least.
So here is the query I wrote.
SELECT students.first_name, students.last_name, scores.score
FROM students
LEFT JOIN scores
ON students.id = scores.student_id
WHERE scores.item_id =1
In my mind this should work, it should pull all the students even if there is no score for them because it is a left join but it is only pulling the one student with a score Eric Larsen, The results looks like
Eric, Larsen, 20
But shouldn’t it be:
first_name last_name score
----------------------------
Eric Larsen 20
Sam Coons NULL
David Brown NULL
Richard Brown NULL
Kendra Griffiths NULL
?
This query will reveal your problem.
You see
scores.item_idisNULLfor all those other rows, so that fails yourWHERE scores.item_id = 1clause, hence those rows not appearing in your results.This should get the results you are after
or