选择命令字段必须等于某个值,但另一个字段可以有2个值

时间:2015-11-03 02:43:05

标签: mysql sql asp.net

我有以下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 3team.status Completed的用户可以是NULLteams.status。但是,此查询会显示CompletedNULLselect_all的所有角色。任何有助于解决此问题的帮助将不胜感激。

2 个答案:

答案 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)