简体   繁体   English

左外连接不会从我的左表中返回所有行?

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

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 tracking ON day.days = DAY(FROM_UNIXTIME(open_date)) 
WHERE tracking.open_id = 10 
GROUP BY day.days

The output I get it is this:我得到的输出是这样的:

days opens
1   9
9   2

The thing is, in my day table, I have a single column that contains the number 1 to 30 to represent the days in a month.问题是,在我的日期表中,我有一列包含数字 1 到 30 来表示一个月中的天数。 I did a left outer join and I am expecting to have all days show on the days column!我做了一个左外连接,我期待在天数列中显示所有天数!

But my query is doing that, why might that be?但我的查询正在这样做,为什么会这样?

Thanks all for any help.感谢大家的帮助。

Nanne's answer given explains why you don't get the desired result (your WHERE clause removes rows), but not how to fix it. Nanne给出的答案解释了为什么你没有得到想要的结果(你的 WHERE 子句删除了行),但没有解释如何解决它。

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:解决方案是将 WHERE 更改为 AND 以便条件是连接条件的一部分,而不是连接后应用的过滤器:

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.现在左表中的所有行都将出现在结果中。

您指定连接的 tracking.open_id 必须为 10。对于其他行,它将为 NULL,因此它们不会显示!

The condition is in the WHERE clause.条件在WHERE子句中。 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.加入表后,评估 WHERE 条件以过滤掉所有符合条件的内容。因此,任何不匹配tracking.open_id = 10都会被丢弃。

If you want to apply this condition while joining the two tables, a better way is to use it with the ON clause (ie joining condition) than the entire dataset condition.如果要在连接两个表时应用此条件,与整个数据集条件相比,更好的方法是将其与ON子句(即连接条件)一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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