0

我在这里发起了一个查询,该查询对检索与连接不匹配的结果做了一些特别的事情(如this SO question所建议的那样)。

SELECT cf.f_id
FROM comments_following AS cf
INNER JOIN comments AS c ON cf.c_id = c.id
WHERE NOT EXISTS (
    SELECT 1 FROM follows WHERE f_id = cf.f_id
)

关于如何加快速度的任何想法?它正在查看 30k-200k 行,并且似乎正在使用索引,但查询超时。

解释/描述信息:

1   PRIMARY c   ALL PRIMARY NULL    NULL    NULL    39119   
1   PRIMARY cf  ref c_id, c_id_2    c_id    8   ...c.id 11  Using where; Using index
2   DEPENDENT SUBQUERY  following   index   NULL    PRIMARY 8   NULL    35612   Using where; Using index
4

3 回答 3

1

LEFT JOIN 有时比 WHERE NOT EXISTS 子查询更快,请尝试:

SELECT cf.f_id
FROM comments_following AS cf
INNER JOIN comments AS c ON cf.c_id = c.id
LEFT JOIN follows AS f ON f.f_id = cf.f_id
WHERE f.f_id IS NULL
于 2013-05-31T20:33:44.140 回答
1

comments表未在查询中显式使用。是用来过滤的吗?如果没有,请尝试:

SELECT cf.f_id
FROM comments_following cf
WHERE NOT EXISTS (
    SELECT 1 FROM follows WHERE follows.f_id = cf.f_id
)

顺便说一句,如果这会产生语法错误(因为 follow.f_id 不存在),那就是问题所在。在这种情况下,您会认为您有一个相关的子查询,但实际上并没有。

left outer join版本:

SELECT cf.f_id
FROM comments_following cf left outer join
     follows f
     on f.f_id = cf.f_id
where f.f_id is null

启用索引follows(f_id)应该会使这两个版本运行得更快。

于 2013-05-31T22:07:16.577 回答
0

这个问题的答案是在follows.f_id.

于 2013-05-31T23:08:41.587 回答