我有以下SQL查询:
SELECT users.user_id,
users.first_name,
users.last_name,
roles.role,
roles.role_id,
users.username,
users.description,
users_vs_teams.team_id,
teams.team_name,
teams.status
FROM users
INNER JOIN roles ON users.role_id = roles.role_id
INNER JOIN users_vs_teams ON users.user_id = users_vs_teams.user_id
INNER JOIN teams ON users_vs_teams.team_id = teams.team_id
WHERE( users.role_id = 3 )
此查询显示用户角色为3的所有用户以及由于他们user_id
出现在users_vs_teams
表中而被分配给sprint的团队。但是,我希望显示与此相反的位置,它显示角色为3但在user_id
表中找不到users_vs_teams
的用户。
非常感谢任何帮助。
答案 0 :(得分:1)
SELECT users.user_id,
users.first_name,
users.last_name,
roles.role,
roles.role_id,
users.username,
users.description
FROM users
INNER JOIN roles ON users.role_id = roles.role_id
LEFT JOIN users_vs_teams ON users.user_id = users_vs_teams.user_id
WHERE users.role_id = 3
AND users_vs_teams.user_id IS NULL
答案 1 :(得分:0)
SELECT users.user_id, users.first_name, users.last_name, roles.role, roles.role_id, users.username, users.description, users_vs_teams.team_id, teams.team_name, teams.status
FROM users INNER JOIN roles ON users.role_id = roles.role_id
INNER JOIN users_vs_teams ON users.user_id <> users_vs_teams.user_id
INNER JOIN teams ON users_vs_teams.team_id = teams.team_id
WHERE (users.role_id = 3)
答案 2 :(得分:0)
更改为左外连接并向where子句添加另一个条件。左外连接从左侧的表(此处为用户)中提取所有行,并且条件确保只有那些行出现在右侧表中没有合适匹配的位置(此处为users_vs_teams)。在以下查询中,您必须更改&#34; pk&#34;在附加的where子句条件中,实际列是users_vs_teams表的主键。
SELECT users.user_id, users.first_name, users.last_name, roles.role, roles.role_id, users.username, users.description, users_vs_teams.team_id, teams.team_name, teams.status
FROM users
INNER JOIN roles ON users.role_id = roles.role_id
INNER JOIN teams ON users_vs_teams.team_id = teams.team_id
LEFT OUTER JOIN users_vs_teams ON users.user_id = users_vs_teams.user_id
WHERE (users.role_id = 3)
AND users_vs_teams.pk IS NULL
答案 3 :(得分:0)
使用LEFT JOIN
代替NULL
表中的所有users_vs_teams
个ID,在AND users_vs_teams.user_id IS NULL
子句中添加WHERE
,您可以得到你想要的东西。
SELECT users.user_id,
users.first_name,
users.last_name,
roles.role,
roles.role_id,
users.username,
users.description,
users_vs_teams.team_id,
teams.team_name,
teams.status
FROM users
INNER JOIN roles ON users.role_id = roles.role_id
INNER JOIN teams ON users_vs_teams.team_id = teams.team_id
LEFT JOIN users_vs_teams ON users.user_id = users_vs_teams.user_id
WHERE( users.role_id = 3 )
AND users_vs_teams.user_id IS NULL