SQL查询加入四个表

时间:2014-07-27 15:54:46

标签: mysql sql

User table - user Id, first name, last name
Investment table - investment Id, investment Name
NDA table- investment Id, user Id, NDA signed(boolean)
Permission table - investment Id, user Id, view permission(boolean)

我需要的结果 - 对于特定投资ID,具有NDA签名或查看权限为true / false的用户的名字和姓氏。

输入 - 投资标识

输出 - 名字,姓氏,签署的NDA(真/假),查看权限(真/假)

我得到了输出是名字,姓氏,NDA签名的查询

SELECT u.First_Name, u.Last_Name, n.Nda_Signed 
FROM user u 
JOIN nda n ON u.User_Id = n.User_Id 
JOIN investment i ON i.Investment_Id = n.Investment_Id 
WHERE i.Investment_Id =347

但在加入nda和权限表时遇到问题。

1 个答案:

答案 0 :(得分:1)

我会这样做:

select u.user_id,
       u.first_name,
       u.last_name,
       sum(case when typ = 'nda' and yesno = 1 then 1 else 0 end) as nda_signed,
       sum(case when typ = 'per' and yesno = 1 then 1 else 0 end) as vw_perm
  from user u
  join (select investment_id, user_id, nda_signed as yesno, 'nda' as typ
          from nda
        union all
        select investment_id, user_id, view_permission, 'per'
          from permission) x
    on u.user_id = x.user_id
where investment_id = 'xyz'
group by u.user_id,
       u.first_name,
       u.last_name

内联视图(x)合并nda和权限表,并通过typ列指示每行的源。内联视图连接回user_id上的用户表。然后你可以有条件地聚合找到nda_signed和view_perm 1/0。