条件SQL从几个表加入

时间:2017-05-09 09:29:57

标签: sql join

我有三个连接的表。我需要做一个单独的SQL选择,我知道我需要使用某种形式的连接但不是如何。如果userID的会话可以访问该对象的区域(如果公司有权访问该区域,则用户可以访问)我只希望选择objectID我拥有的表是:

+----------+--------+ Objects
| objectID | areaID |
+----------+--------+
|        1 |      2 |
|        2 |      2 |
|        3 |      3 |
+----------+--------+
+-----------+--------+ Users
| companyID | userID |
+-----------+--------+
|         1 |      1 |
|         1 |      2 |
|         1 |      3 |
+-----------+--------+
+-----------+--------+ Access
| companyID | areaID |
+-----------+--------+
|         1 |      1 |
|         1 |      2 |
|         1 |      3 |
+-----------+--------+

2 个答案:

答案 0 :(得分:1)

使用companyID在inner query中选择UserID和相应的areaID。然后使用此选项,从Objects表中选择不同的ObjectID,再次使用内部连接与通过inner query

形成的表

尝试此查询: -

Select distinct a.objectID 
from
Objects a
inner join
(
Select a.*,b.areaID
from
Users a
inner join
Access b
on a.companyID=b.companyID
) b
on a.areaID=b.areaID
Where b.UserID= 1;

答案 1 :(得分:0)

如果我理解你的话,似乎有两个INNER JOIN函数可以获得你想要的结果:

WITH ONE AS (
    SELECT a.companyID, a.userID, b.areaID
    FROM Users a
    INNER JOIN Access b
    ON a.companyID = b.companyID
    )

SELECT a.companyID, a.userID, a.areaID, b.objectID
FROM ONE a
INNER JOIN Objects b
ON a.areaID = b.areaID;

编辑:回复评论

如果要将结果限制为特定的userID值,则需要WHERE子句:

WITH ONE AS (
    SELECT a.companyID, a.userID, b.areaID
    FROM Users a
    INNER JOIN Access b
    ON a.companyID = b.companyID
    )

SELECT a.companyID, a.userID, a.areaID, b.objectID
FROM ONE a
INNER JOIN Objects b
ON a.areaID = b.areaID
WHERE a.userID = ${specific_user_id};