下面的连接语句有效吗?
这个连接在 MySQL 中是否有效:
FROM a
JOIN b on a.c = b.c and b.c = 1
它确实像这样工作,但是当我使用 RIGHT JOIN 时,bc = 1 被忽略。 这是为什么?
Is this join valid in MySQL:
FROM a
JOIN b on a.c = b.c and b.c = 1
Well it does work like this but when I use a RIGHT JOIN the b.c = 1 is ignored.
Why is that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在
RIGHT JOIN
中不会忽略它。(概念上)联接发生在应用了过滤器的情况下,然后
b
中的任何不匹配行都会被添加回来。因此查询
返回
您可以看到,尽管事实上两个表都有
2 join 子句中的附加过滤器意味着这些行不会被连接。然而,由于它是
右外
连接,右侧表中的2
行(b
)仍然出现在结果中。编辑:回复:评论中的问题
我实在不明白这个问题。
您可以根据是否要保留左侧输入或右侧输入中的所有行来选择
LEFT
与RIGHT
连接。对于简单的 2 表查询,您当然可以使用其中任何一个,只需颠倒表的顺序即可。对于是否将过滤器放在
WHERE
子句或JOIN
条件中的问题也类似。在OUTER JOIN
中,这可以更改结果(在我的示例中,将bc = 1
数据移动到WHERE
子句意味着只有 1 行将被返回不是 2)对于
INNER JOIN
的情况,过滤器放置在哪里并不重要,但我发现将与JOIN< 中的 2 个表之间的关系相关的过滤器放在一起更明智/code> 和所有其他在
哪里
It isn't ignored in a
RIGHT JOIN
.(Conceptually) The Join happens with the filter applied then any non matching rows from
b
get added back in.So the query
Returns
You can see that despite the fact both tables have a
2
the additional filter in thejoin
clause means that these rows don't get joined. However as it is aright outer
join the2
row from the right hand table (b
) still appears in the results.Edit: RE: Question in comments
I don't really understand this question.
You would choose
LEFT
vsRIGHT
join on the basis of whether you wanted to preserve all rows from the left input or the right input. For a simple 2 table query you can of course use either and just reverse the order of the tables.Similarly for the issue of whether to put the filter in the
WHERE
clause or theJOIN
condition. In anOUTER JOIN
this can change the results (In my example data movingb.c = 1
to theWHERE
clause means that only 1 row will be returned not 2)For the case of
INNER JOIN
it does not matter where the filters are placed but I find it more sensible to put filters concerned with the relationship between the 2 tables in theJOIN
and all others in theWHERE
是的。
on
子句中可以有与其他表无关的额外条件Yes. It's OK to have extra conditions in the
on
clause that have nothing to do with other tables是的,它是有效的。
但是,当您使用右连接时,除了满足连接条件的值之外,您还将有效地获取“右”表中不满足连接条件的所有值。这就是右连接的作用。
在这种情况下,使用 where 子句来限制从表 b 中提取的内容。
来自
在 ac = bc 上右连接 b,其中 bc = 1
Yes it is valid.
However when you use a right join, you will effectively get all the values in the "right" table that doesn't satisfy the join condition in addition to those who do. That's what right join does
Use a where clause to restrict what you pull out of table b in that case.
FROM a
RIGHT JOIN b on a.c = b.c WHERE b.c = 1
为什么不这样写以使其更清楚:
Why not write it like this to make it clearer: