Based on some googling and this question here Join vs. sub-query, it seems that its recomended to use join instead of nested query, hence I'm trying to enhance what I'm doing.
This is something like a file system, imagine a few tables below.
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
And linking table below
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)
The goal is to query out which folder can be accessed by Jack, hence I'm using below:
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
)
);
The above basically can get me exactly what I needed, but such nested query may cause performance issue in future. Does anyone has any recommendation on how to make this a join instead of nested query?