[英]How can I include rows with a column value greater than what is returned in a SQL query that utilizes inner joins?
I have three tables:我有三张桌子:
Users用户
id Username
---------------------------
1 | John
2 | Mark
Positions职位
id Position Authority Department
---------------------------------------------------------------
1 | Supervisor | 3 4
2 | Clerk | 4 2
3 | Supervisor | 3 2
4 | Admin | 4 4
5 | Assistant | 5 2
UserPositions用户职位
user_id position_id
----------------------------
1 | 1
2 | 3
The tables Users and Positions are related to each other using the UserPositions table, which connects them via the id (a foreign key) of each table.表 Users 和 Positions 使用 UserPositions 表相互关联,该表通过每个表的 id(外键)连接它们。
I'm trying to get results back that include anything greater than or equal to the authority and department a user is assigned to.我正在尝试获取结果,其中包括大于或等于分配给用户的权限和部门的任何内容。 So far, I was able to work out this query:到目前为止,我能够解决这个查询:
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
Which returns:返回:
Username Position Authority Department
---------------------------------------------------------------
John | Supervisor | 3 | 4
Mark | Supervisor | 3 | 2
However, I want to include positions for that user that are in the same department but also greater than the authority that the user was assigned.但是,我想包括该用户的职位,这些职位位于同一部门,但也大于该用户被分配的权限。 For example, John has been assigned the position Supervisor which is in department 4 and authority 3. So I want to return a list of all positions that are in department 4 and have authority of 3 or greater and have it listed next to John.例如,John 被分配了 position 主管,该主管在部门 4 和权限 3 中。所以我想返回部门 4 中所有职位的列表,并且权限为 3 或更大,并将其列在 John 旁边。 The same for Mark.马克也是一样。 Like this:像这样:
Username Position Authority Department
---------------------------------------------------------------
John | Supervisor | 3 | 4
John | Admin | 4 | 4
Mark | Supervisor | 3 | 2
Mark | Clerk | 4 | 2
Mark | Assistant | 5 | 2
How can I modified my query above to get this result?如何修改上面的查询以获得此结果?
I think that's another join:我认为这是另一个加入:
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
Notes:笔记:
I turned the left join
s to inner join
;我将left join
转为inner join
; nothing in your problem statement indicates that you want the former您的问题陈述中没有任何内容表明您想要前者
Meaningful table aliases make the queries easier to follow有意义的表别名使查询更容易理解
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.