mysql 左连接查询
我对下面的代码片段有疑问。我想知道,如果第一个查询没有带来任何结果,我还会得到第二个查询的结果吗?
select *
from
(
-- first query
) as query1
left join
(
-- second query
) as query2
on query1.id=query2.id
left join
(
-- third query
) as query3
on query1.id=query3.id;
更新:
我需要的是完全连接,但是MySQL不支持它,什么是模拟这个的好方法?
I have a question about the snippet below. I'm wondering, if the first query doesn't bring any results, would I still get the results for the second query?
select *
from
(
-- first query
) as query1
left join
(
-- second query
) as query2
on query1.id=query2.id
left join
(
-- third query
) as query3
on query1.id=query3.id;
Update:
what I need is a full join, however, MySQL does not support it, what would be a good way to emulate this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
答案是否定的。
左连接将从左侧提取所有结果,并且仅提取右侧匹配的结果。右连接则相反。完整外部联接将从任一结果中提取所有结果,并仅联接那些可以联接的结果。
请注意,对于当前的数据库,明智的做法是避免完全外连接,因为它们的效率比其他连接低得多。我个人已经成功地用这样的技巧击败了 Oracle 和 PostgreSQL 中的完全外连接,这些技巧也可以用于模拟没有它们的数据库中的完全外连接:
有可能这个查询不会按原样工作是因为数据库无法确定空列的类型。有一些解决方法。最简单的方法是创建一个具有显式列类型的临时表,使用 2 个插入查询模拟 UNION ALL,然后从临时表中进行查询。
(参见http://bentilly.blogspot.com/2011/02/sql -formatting-style.html 来解释我的格式化风格。)
The answer is no.
A left join will pull all results from the left, and only those results on the right that match. A right join does the reverse. A full outer join will pull all results from either and join just those that can be joined.
Note that with current databases it is wise to avoid full outer joins because they are much less efficient than other joins. I have personally managed to beat full outer joins in Oracle and PostgreSQL by orders of magnitude with tricks like this, which can also be used to emulate full outer joins in databases that don't have them:
There is a possibility that this query will not work as is because the database won't figure out the types of the null columns. There are workarounds for that. The simplest is to create a temp table with explicit column types, emulate the UNION ALL with 2 insert queries, then query off of the temp table.
(See http://bentilly.blogspot.com/2011/02/sql-formatting-style.html for an explanation of my formatting style.)
不,您需要进行右连接。
No, you would need to do a right join instead.
否,因为第二个查询的结果会附加到第一个查询的结果中。
No, because results from the second query appends to the results from the first query.
否,因为您已离开加入。第二个记录将添加到第一个记录。如果没有第一个,则不能添加第二个记录。通过右连接可以实现反转。
No because you have left join. Records from second are added to first. If there are no first no record from second can be added. Revers is possible via right join.