您好,我有几个表用于仪表板,用户,user_dahboard,user_organisation。下面是表架构。
dashboard_user
id user_id dashboard_id
1 2 1
2 1 1
3 4 2
4 1 2
org_user
id user_id org_id
1 1 1
2 2 1
3 3 2
4 4 2
仪表板
id dashboard_title
1 World's Bank Data
2 Births
3 Unicode Test
现在,我想从同一组织用户获取所有仪表板。像用户ID 1一样,可以看到同一组织用户开发的所有仪表板。我做了以下查询相同
SELECT
dashboards.id AS dashboards_id
FROM
dashboards
JOIN dashboard_user AS dashboard_user_1 ON dashboards.id = dashboard_user_1.dashboard_id
JOIN organization_user AS organization_user_1 ON organization.id = organization_user_1.org_id
JOIN ab_user ON ab_user.id = dashboard_user_1.user_id
WHERE ab_user.id = 1
类似于条件条件usr_id = 1的预期结果,它应返回所有属于与user1具有相同组织的用户的dashboard_id。
结果
user org dashboard
1 1 1
2 1 2
最佳答案
我不确定是否需要任何JOIN
。如果只希望给定用户的仪表板:
SELECT du.dashboards_id
FROM dashboard_user du
WHERE du.user_id = 1;
如果希望与
user_id = 1
来自同一组织的所有仪表板,则:SELECT DISTINCT du.dashboards_id
FROM dashboard_user du
WHERE du.user_id IN (SELECT ou.user_id
FROM org_user ou JOIN
org_user ou1
ON ou.org_id = ou1.org_id
WHERE ou1.user_id = 1
);
或者,作为
JOIN
:SELECT DISTINCT du.dashboards_id
FROM dashboard_user du JOIN
org_user ou
ON du.user_id = ou.user_id JOIN
org_user ou1
ON ou1.org_id = ou.ord_id AND
ou1.user_id = 1
关于mysql - 如何正确加入?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57132308/