来自多个JOIN的多个表的SQL查询

时间:2015-06-06 09:52:28

标签: mysql sql

我有以下数据库,其中用户帐户详细信息存储在Users表中,组织详细信息通过'UsersOrganisation_Map'联结表链接到用户,用户权限通过UsersSiteRoles_Map联结表链接到用户。数据库是MySQL

我正在努力解决的问题是如何在单个查询中从角色和组织表中获取数据,并将结果返回,就像它们来自单个表一样。

这是一个示例脚本(不起作用),希望能够描述我想要实现的目标。

> select * from UsersOrganisation_Map, UsersSiteRoles_Map join Users on
> UsersOrganisationMap.userID = Users.userID join Organisation on
> UsersOrganisationMap.organisationID = Organisation.organisationID
> where userEmail = 'admin@test.com' AND userPassword = 'test' AND
> accountActive = 'YES' join Users on UsersSiteRoles_Map.userID =
> Users.userID join SiteRoles on UsersSiteRoles_Map.roleID =
> SiteRoles.roleID

enter image description here

2 个答案:

答案 0 :(得分:2)

这应该类似于:

SELECT
    u.*,
    usr.*,
    sr.*,
    uom.*,
    o.*
FROM
    Users as u
JOIN UsersSiteRoles_Map as usr
    ON u.userID = usr.UserId
JOIN SiteRoles as sr
    ON UsersSiteRoles_Map.roleID = sr.roleID
JOIN UsersOrganisation_Map as uom
    ON u.userID = uom.userID
JOIN Organisation as o
    ON o.organisationID = uom.Id
WHERE
    u.userEmail = 'admin@test.com'
    AND u.userPassword = 'test'
    AND u.accountActive = 'YES'

答案 1 :(得分:0)

您只需将所有五个表连接在一起,如:

SELECT *
FROM Users u
-- join to get roles
JOIN UsersSiteRoles_Map ur ON u.id=ur.user_id
JOIN SiteRoles r ON um.role_id=r.id
-- join to get organisation
JOIN UsersOrganisation_Map uo ON u.id=uo.user_id
JOIN Organisation o ON uo.organisation_id=o.id
-- filter results
WHERE u.email=admin ...