如何使用左连接使我的查询更快?
How do I make my query using left join to be faster?
我有三个表:用户 (id)、项目 (id_project、owner_id) 和关注者 (repo_id、user_id)。我想统计一个项目有多少关注者。我想要 return 所有用户项目,有和没有关注者。
其中:
id = owner_id = user_id
id_project = repo_id
我在查询中报告了 1,000 多个用户。我这样做了:
rs = dbSendQuery(mydb, "select p.id_project, p.owner_id, count(f.user_id) from users u left outer join projects p on p.owner_id = u.id and u.id in (123, 526, 852) left outer join followers f on p.id_project = f.repo_id group by p.id;")
查询速度太慢。谁能给我任何建议以加快查询速度?我做错了什么吗?
也许,我可以分成两个查询,但我如何获得第一个(用户的项目)的结果并添加第二个查询(我将在其中获得关注者的数量)项目)在 R 中?
我正在使用 R 和 mysql。
此致,
萨恰纳
有时切换到相关子查询可以加快此类查询的速度:
select p.id_project, p.owner_id, count(f.user_id)
from users u left outer join
projects p
on p.owner_id = u.id and u.id in (123, 526, 852) left outer join
followers f
on p.id_project = f.repo_id
group by p.id;
对于此查询,您需要在 users(id)
、projects(owner_id, id_project)
和 followers(repo_id, user_id)
上建立索引。
我注意到您并没有真正使用 users
table。所以,这应该做你想做的事:
select p.id_project, p.owner_id, count(f.user_id)
from projects p left outer join
followers f
on p.id_project = f.repo_id
where p.owner_id in (123, 526, 852)
group by p.id;
相同的索引应该适用于此查询,尽管 users
上的索引显然不需要。
接下来,在MySQL中,关联子查询有时比聚合查询更快。所以,你可以试试:
select p.id_project, p.owner_id,
(select count(*)
from followers f
where p.id_project = f.repo_id
) as num_followers
from projects p
where p.owner_id in (123, 526, 852);
我有三个表:用户 (id)、项目 (id_project、owner_id) 和关注者 (repo_id、user_id)。我想统计一个项目有多少关注者。我想要 return 所有用户项目,有和没有关注者。
其中: id = owner_id = user_id id_project = repo_id
我在查询中报告了 1,000 多个用户。我这样做了:
rs = dbSendQuery(mydb, "select p.id_project, p.owner_id, count(f.user_id) from users u left outer join projects p on p.owner_id = u.id and u.id in (123, 526, 852) left outer join followers f on p.id_project = f.repo_id group by p.id;")
查询速度太慢。谁能给我任何建议以加快查询速度?我做错了什么吗?
也许,我可以分成两个查询,但我如何获得第一个(用户的项目)的结果并添加第二个查询(我将在其中获得关注者的数量)项目)在 R 中?
我正在使用 R 和 mysql。
此致, 萨恰纳
有时切换到相关子查询可以加快此类查询的速度:
select p.id_project, p.owner_id, count(f.user_id)
from users u left outer join
projects p
on p.owner_id = u.id and u.id in (123, 526, 852) left outer join
followers f
on p.id_project = f.repo_id
group by p.id;
对于此查询,您需要在 users(id)
、projects(owner_id, id_project)
和 followers(repo_id, user_id)
上建立索引。
我注意到您并没有真正使用 users
table。所以,这应该做你想做的事:
select p.id_project, p.owner_id, count(f.user_id)
from projects p left outer join
followers f
on p.id_project = f.repo_id
where p.owner_id in (123, 526, 852)
group by p.id;
相同的索引应该适用于此查询,尽管 users
上的索引显然不需要。
接下来,在MySQL中,关联子查询有时比聚合查询更快。所以,你可以试试:
select p.id_project, p.owner_id,
(select count(*)
from followers f
where p.id_project = f.repo_id
) as num_followers
from projects p
where p.owner_id in (123, 526, 852);