用join替换嵌套查询

问题描述 投票:0回答:2

基于一些谷歌搜索和这个问题在这里qazxsw poi,似乎建议使用连接而不是嵌套查询,因此我试图增强我正在做的事情。

这就像文件系统,想象下面的几个表。

Join vs. sub-query

并链接下面的表格

user               group           folder
==========         ==========      ==========  
id   name          id   name       id   name 
==========         ==========      ==========
 1   Jack           1   HR          1   Staff Policies                             
 2   James          2   Sales       2   Contracts                              
 3   Joe            3   IT          3   Documentations                           

目标是查询Jack可以访问哪个文件夹,因此我在下面使用:

group_user
===================
groupId    userId
===================
1           1  (Jack works in HR)                                                                                                                
1           2  (James works in HR)                                                                                       
3           3  (Joe works in IT)                                                                                                          
3           1  (Jack also works in IT)                                                                                           

group_folder
====================
groupId    folderId
====================
1          1   (HR can access Staff Policies)
1          2   (HR can access Contracts)                                                                            
3          3   (IT can access Documentations)
1          3   (HR can also access Documentations)

以上基本上可以得到我所需要的,但是这样的嵌套查询将来可能会导致性能问题。有没有人有任何关于如何使这个连接而不是嵌套查询的建议?

mysql
2个回答
1
投票

您基本上通过INNER JOIN将所有内容放在一起,使用与查询中SELECT f.id, f.name FROM folder f WHERE f.ID IN ( SELECT gf.folderId FROM group_folder gf WHERE gf.groupId in ( SELECT gu.groupId FROM group_user gu WHERE gu.userId = 1 ) ); 相同的约束,但这里使用的是IN。最后,您可以添加ON子句以仅选择您需要的行:

WHERE

-1
投票

从您的查询中,您将获得userid = 1具有的文件夹,实际查询需要group by子句,尝试这个,它获取您的查询得到的相同数据

SELECT f.id, f.name
FROM folder f
INNER JOIN group_folder gf ON f.ID = gf.folderID
INNER JOIN group_user gu ON gf.groupID = gu.groupID
WHERE gu.userId = 1
© www.soinside.com 2019 - 2024. All rights reserved.