MySQL涉及疯狂的多重自连接
作为替换一些使用极其缓慢的嵌套选择的旧代码的过程的一部分,我最终得到了一个如下所示的查询:
SELECT r3.r_id AS r3_id, r2.r_id AS r2_id, r1.r_id AS r1_id
FROM
table_r r3
LEFT JOIN (
table_r r2
INNER JOIN (
table_r r1
INNER JOIN table_d d ON r1.r_id = d.r_id
) ON r2.r_id = r1.parent_id
) ON r3.r_id = r2.r_id
WHERE d.d_id = 3
因此,在最内层联接中,我正在查找 table_r< 中的记录/code>(复制
r1
),与table_d
中的记录子集有关系。
在下一次连接中,我在 table_r
(r2
) 的第二个副本中查找记录,其主索引 (r_id
) 与上一个连接的记录的父索引 (parent_id
)。
然后我尝试使用 table_r
(r3
) 的第三个副本进行 LEFT JOIN
,只需匹配 r_id
> 与前一个连接的 r_id
。这个最外层连接的想法是从 table_r
获取所有记录,然后通过使用进一步的条件(尚未在我的查询)来确定 r3
中的哪些记录的 r2_id
具有 NULL
。
问题是 LEFT JOIN 没有给我整个 table_r 。它为我提供了在没有最终连接的情况下获得的相同记录子集 - 换句话说,与 INNER JOIN
相同。所以,虽然我期待 1208 条记录,但我得到了 508 条。
我知道我一定在这里做了一些奇怪的事情......
As part of the process of replacing some old code that used an incredibly slow nested select, I've ended up with a query that looks like this:
SELECT r3.r_id AS r3_id, r2.r_id AS r2_id, r1.r_id AS r1_id
FROM
table_r r3
LEFT JOIN (
table_r r2
INNER JOIN (
table_r r1
INNER JOIN table_d d ON r1.r_id = d.r_id
) ON r2.r_id = r1.parent_id
) ON r3.r_id = r2.r_id
WHERE d.d_id = 3
So in the innermost join, I'm looking for the records in table_r
(copy r1
) which have a relationship with a subset of records from table_d
.
In the next join out, I'm looking for records in a second copy of table_r
(r2
) whose main index (r_id
) matches the parent index (parent_id
) of the records from the previous join.
Then I'm trying to do a LEFT JOIN
with a third copy of table_r
(r3
), simply matching r_id
with the r_id
of the previous join. The idea of this outermost join is to get ALL of the records from table_r
, but to then do the equivalent of a NOT IN
select by using a further condition (not yet in my query) to determine which records in r3
have NULLs
for r2_id
.
The problem is that the LEFT JOIN
is not giving me the whole of table_r
. It's giving me the same subset of records that I get without the final join - in other words, the same thing as an INNER JOIN
. So whereas I'm expecting 1208 records, I get 508.
I know I must be doing something screwy here...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果你尝试这样做会发生什么?
我所做的是将 d.d_id = 3 从 where 子句移至 INNER JOINs ON 限定符。
What happens, if you try this?
What I did was moved the d.d_id = 3 from where clause to the INNER JOINs ON qualifiers.