加入多个表格

时间:2015-09-03 08:10:12

标签: mysql sql

我有以下表格:

  1. comitees [ID,Name,Total_Amount,Total_Members,Starting_Date,Ending_Date]

  2. committee_group [Id,Name,Total_Members]

  3. Group_Member [Id,Group_Id,Member_Name,Contribution]

  4. 我想从committee_group中选择姓名,其中Group_Member的贡献总和等于来自comitees的Total_Amount

    这是我到目前为止所拥有的

    SELECT committee_group.*, Sum(Case When group_member.Group_Id='1'
                                       THEN group_member.Contribution
                                       ELSE 0 END) 
    FROM committee_group
      LEFT JOIN group_member ON group_member.Id = committee_group.Id
      LEFT join comitees ON group_member.Contribution = comitees.Total_Amount
    

1 个答案:

答案 0 :(得分:0)

这应该有效,

SELECT a.id,a.Name,a.Total_Members,c.Total_Amount
FROM committee_Group a
INNER JOIN (SELECT Name,sum(Contribution) as 'Sum_Con'
            FROM Group_Member
            GROUP BY Name)b on a.Id=b.Id
INNER JOIN comitees c on c.Total_Amount=b.Sum_Con
                     and b.Name=c.Name