如何包含列值大于使用内部联接的 SQL 查询中返回值的行?

How can I include rows with a column value greater than what is returned in a SQL query that utilizes inner joins?

我有三个table:

用户

id          Username
---------------------------
1     |     John
2     |     Mark

职位

id          Position          Authority          Department 
---------------------------------------------------------------
1     |     Supervisor    |       3                  4
2     |     Clerk         |       4                  2    
3     |     Supervisor    |       3                  2
4     |     Admin         |       4                  4
5     |     Assistant     |       5                  2

用户职位

user_id          position_id 
----------------------------
1               |     1 
2               |     3 

tables Users 和 Positions 使用 UserPositions table 相互关联,通过每个 table 的 id(外键)连接它们。

我正在尝试取回结果,其中包括大于或等于用户分配到的权限和部门的任何内容。到目前为止,我能够计算出这个查询:

SELECT A.Username, B.Position, B.Authority, B.Department FROM UserPositions C
LEFT JOIN Users A on C.user_id = A.Id
LEFT JOIN Positions B on C.position_id = B.Id

哪个 returns:

Username         Position          Authority          Department 
---------------------------------------------------------------
John        |     Supervisor   |      3           |       4
Mark        |     Supervisor   |      3           |       2

但是,我想包括该用户的职位,这些职位属于同一部门,但也高于为该用户分配的权限。例如,John 已被分配到部门 4 和权限 3 的职位主管。所以我想 return 部门 4 中的所有职位的列表,并且权限为 3 或更高,并在下一个列出给约翰。马克也一样。像这样:

Username         Position          Authority          Department 
---------------------------------------------------------------
John        |     Supervisor   |      3           |       4
John        |     Admin        |      4           |       4
Mark        |     Supervisor   |      3           |       2
Mark        |     Clerk        |      4           |       2
Mark        |     Assistant    |      5           |       2

如何修改上面的查询以获得此结果?

我认为这是另一个加入:

select u.username, p1.position, p1.authority, p1.department 
from userpositions   up
inner join users     u  on u.id = up.user_id
inner join positions p  on p.id = up.position_id
inner join positions p1 on p1.department = p.department and p1.authority >= p.authority

备注:

  • 我把left joins变成了inner join;你的问题陈述中没有任何内容表明你想要前者

  • 有意义 table 别名使查询更容易理解