Left Outer Join doesn't return all rows from my left table?

后端 未结 3 1974
陌清茗
陌清茗 2020-11-21 10:23

I am trying to get the number of page opens on a per day basis using the following query.

SELECT day.days, COUNT(*) as opens 
FROM day 
LEFT OUTER JOIN track         


        
相关标签:
3条回答
  • 2020-11-21 10:35

    You specify that the connected tracking.open_id must be 10. For the other rows it will be NULL, so they'll not show up!

    0 讨论(0)
  • 2020-11-21 10:37

    The condition is in the WHERE clause. After joining the tables the WHERE conditions are evaluated to filter out everything matching the criteria.Thus anything not matching tracking.open_id = 10 gets discarded.

    If you want to apply this condition while joining the two tables, a better way is to use it with the ON clause (i.e. joining condition) than the entire dataset condition.

    0 讨论(0)
  • 2020-11-21 10:44

    Nanne's answer given explains why you don't get the desired result (your WHERE clause removes rows), but not how to fix it.

    The solution is to change WHERE to AND so that the condition is part of the join condition, not a filter applied after the join:

    SELECT day.days, COUNT(*) as opens 
    FROM day 
    LEFT OUTER JOIN tracking
    ON day.days = DAY(FROM_UNIXTIME(open_date)) 
    AND tracking.open_id = 10 
    GROUP BY day.days
    

    Now all rows in the left table will be present in the result.

    0 讨论(0)
提交回复
热议问题