简体   繁体   中英

LEFT JOIN not creating NULL records for unmatched rows

LEFT JOIN supposedly joins 2 tables and creates NULL values when no matching record is found in the second (right) table. In the following timesheet scenario, I can't seem to get that to happen.

users_table:

user_id
-------
frank
joe
jane

timesheet_table:

user_id    month    hours
---------------------------
frank          jan     1
frank          jan     2
frank          jan     3
frank          feb     5
frank          mar     10
joe            jan     8
joe            feb     5
joe            feb     10
jane           jan     5

mysql:

1 SELECT *
2 FROM users_table
3 LEFT JOIN(
4    SELECT
5        timesheet_table.user_id,
6        month,
7        SUM(hours)
8    FROM timesheet_table
9 ) timesheet_summary
10 ON users_table.user_id = timesheet_summary.user_id
11 GROUP BY month, users_table.user_id

Gives me something like this...

user_id    month    hours
---------------------------
frank        jan     6
joe          jan     8
jane         jan     5
frank        feb     5
joe          feb     15
frank        mar     10

But what I hoped for was...

user_id    month    hours
---------------------------
frank        jan     6
joe          jan     8
jane         jan     5
frank        feb     5
joe          feb     15
jane         feb     NULL
frank        mar     10
joe          mar     NULL
jane         mar     NULL

What is REALLY confusing me is that if I add a the following criteria between lines 8 and 9 it works (sort of)!

WHERE month = 'feb'

Gives me...

user_id    month    hours
---------------------------
frank        feb     5
joe          feb     15
jane         feb     NULL

Which is close but not exactly what I'm trying to do.

Actually that's what left join is supposed to do. You must use inner join instead.

See this for an overall idea

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM