我有以下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,
teams.notes
FROM teams
INNER JOIN users_vs_teams ON teams.team_id = users_vs_teams.team_id
RIGHT OUTER JOIN users ON users_vs_teams.user_id = users.user_id
INNER JOIN roles ON users.role_id = roles.role_id
WHERE( users.role_id = 3 ) AND ( teams.status = 'Completed' ) OR ( teams.status IS NULL )
我想只显示role_id
3
但team.status
Completed
的用户可以是NULL
或teams.status
。但是,此查询会显示Completed
为NULL
或select_all
的所有角色。任何有助于解决此问题的帮助将不胜感激。
答案 0 :(得分:1)
首先,我不确定您是否需要外部联接。其次,您的问题似乎是WHERE
子句中的括号:
SELECT u.user_id, u.first_name, u.last_name, r.role, r.role_id,
u.username, u.description, uvt.team_id,
t.team_name, t.status, t.notes
FROM teams t INNER JOIN
users_vs_teams uvt
ON t.team_id = uvt.team_id INNER JOIN
users u
ON uvt.user_id = u.user_id
roles r
ON u.role_id = r.role_id ON u
WHERE (u.role_id = 3) AND (t.status = 'Completed' OR t.status IS NULL)
请注意,表别名使查询更易于编写和阅读。
答案 1 :(得分:0)
删除1<0
并修复RIGHT OUTER JOIN
。
WHERE clause
您也可以这样做:
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,
teams.notes
FROM teams
INNER JOIN users_vs_teams ON teams.team_id = users_vs_teams.team_id
INNER JOIN users ON users_vs_teams.user_id = users.user_id
INNER JOIN roles ON users.role_id = roles.role_id
WHERE( users.role_id = 3 ) AND ( teams.status = 'Completed' OR teams.status IS NULL)