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

发布于 2024-10-12 17:23:01 字数 382 浏览 4 评论 0原文

我试图使用以下查询获取每天打开的页面数。

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

我得到的输出是这样的:

days opens
1   9
9   2

问题是,在我的日期表中,我有一列包含数字 1 到 30 来表示一个月中的天数。我做了一个左外连接,我希望所有的天都显示在天数列上!

但我的查询是这样做的,为什么会这样呢?

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. 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

顾挽 2024-10-19 17:23:02

条件位于 WHERE 子句中。连接表后,将评估 WHERE 条件以过滤掉所有符合条件的内容。因此,任何不匹配 tracking.open_id = 10 的内容都会被丢弃。

如果要在连接两个表时应用此条件,更好的方法是将其与 ON 子句(即连接条件)一起使用,而不是整个数据集条件。

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.

才能让你更想念 2024-10-19 17:23:01

南妮的回答给定解释了为什么您没有得到所需的结果(您的 WHERE 子句删除了行),但没有解释如何修复它。

解决方案是将 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

现在左表中的所有行都将出现在结果中。

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.

[旋木] 2024-10-19 17:23:01

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

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文