SQL查询返回是/否基于具有多个连接的子查询

时间:2014-12-23 17:24:40

标签: mysql sql join subquery

我有一个包含3个表的多对多关系模式:Users,Teams和Teamuser。

由于用户可以在许多团队中,并且团队可以拥有许多用户,因此teamuser是一个将users.id连接到teams.id的表。

我想做一个询问的问题"使用给定的用户ID,向我展示团队表中的所有团队,计算字段名为" member"如果给定用户是该团队的成员,则返回1,否则返回0#34;

有没有办法直接在MySQL中使用一个查询执行此操作?

TeamUser:

id  teamid  userid
5   1 [->]  1 [->]
1   1 [->]  2 [->]
2   2 [->]  2 [->]
6   3 [->]  1 [->]

teamid是加入Teams.id的外键。 userid是Users.id上的外键

队:

id  name
1   Whomping Willows
2   Chudley Cannons

用户:

id  username    
1   fred
2   finn    
3   paul    
16  pickles

4 个答案:

答案 0 :(得分:1)

运行类似下面的内容以获取笛卡尔积,然后执行包含在合并中的相关子选择以指示成员身份?

选择u.username,t.teamname, COALESCE((从teamusers itu中选择1,其中itu.teamid = t.teamid和itu.userid = u.userid),0) 来自用户u,团队 其中u.username =' finn'

警告虽然这不能很好地扩展,因为它从团队用户中选择外部笛卡尔积的每一行。更多团队==更多行来运行子选择

答案 1 :(得分:0)

这是你怎么做的

select
t.id,
t.name,
case when x.userid is not null then 1 else 0 end as `member`
from teams t
left join (
 select 
 tu.userid,
 tu.teamid
 from teamuser tu 
 left join users u on u.id = tu.userid  
 where u.id = 1 -- change the user id here which you are looking at
)x
on x.teamid = t.id

答案 2 :(得分:0)

如果我理解正确,您希望显示两列结果:first = Team ,second = Member 。结果集将包含所有团队,成员列 - 给定用户名是团队成员。然后,您可以使用以下查询:

SELECT a.name AS team_name,
      CASE WHEN c.username = 'fred' THEN 1 ELSE 0 END AS member 
  FROM Teams AS a JOIN TeamUser AS b ON a.id = b.teamid
                  JOIN Users AS c ON b.userid = c.id;

答案 3 :(得分:0)

(实际测试MySQL而不是Oracle后更新。)

你可以一起工作

set @userID = 1;

SELECT
  TeamsOuter.name
  , CASE IFNULL((SELECT Users.id FROM Users JOIN TeamUser ON Users.id = TeamUser.userID JOIN Teams ON TeamUser.teamID = Teams.id WHERE Teams.id = TeamsOuter.id AND Users.id = @userID), 0) WHEN 0 THEN 0 ELSE 1 END member
  , IF((SELECT Users.id FROM Users JOIN TeamUser ON Users.id = TeamUser.userID JOIN Teams ON TeamUser.teamID = Teams.id WHERE Teams.id = TeamsOuter.id AND Users.id = @userID) IS NULL, 0, 1) memberToo
FROM Teams TeamsOuter
;

使用CASEIF 由于问题明确在"对于给定的用户ID [...]",这在查询中使用。

注意:检查结果时:" TeamUser"确实引用了一个拥有" teamID" 3,哪个不存在......

如果您想在一个地方实际拥有所有东西:

SELECT
  UsersOuter.userName
  , TeamsOuter.name
  , IF((SELECT Users.id FROM Users JOIN TeamUser ON Users.id = TeamUser.userID JOIN Teams ON TeamUser.teamID = Teams.id WHERE Teams.id = TeamsOuter.id AND Users.id = UsersOuter.id) IS NULL, 0, 1) member
FROM Teams TeamsOuter, Users UsersOuter
ORDER BY UsersOuter.userName, TeamsOuter.name
;

SQL Fiddle