带连接的复杂SQL

时间:2018-04-27 04:59:53

标签: mysql sql

我在mysql中创建了这三个表。我在创建查询时遇到困难,该查询将向我提供组织列表,其中列出了由他们筹集的资金总额。资金将来自STUDENT AmountRaised和DONORS AmountContributed。任何帮助将不胜感激。

CREATE TABLE STUDENT (
StudentID INT PRIMARY KEY,
StudentFirstName char(100) NOT NULL,
StudentLastName char(100) NOT NULL,
OrgID INT NOT NULL
AmountRaised INT NOT NULL,
Captain Char(3) Null,
);

CREATE TABLE ORGANIZATIONS(
OrgID INT PRIMARY KEY,
OrgName char(100) Not Null,
OrgCategory char(100) Not NULL,
AmountRaised int NOT NULL
);

CREATE TABLE KIDS (
KidId int PRIMARY KEY,
KidFirstName char(100) NOT NULL,
KidLastName char(100) NOT NULL,
OrgID INT NOT NULL,
);

CREATE TABLE DONORS(
DonorID int Primary Key,
DonorFirstName char(100) NOT NULL,
DonorLastName char(100) NOT NULL,
DonorOrganization char(100) NOT NULL,
AmountContributed int NOT NULL,
);

2 个答案:

答案 0 :(得分:0)

看起来像是这样的:

SELECT id, sum(amount) FROM (
    (
        SELECT o.id as id, sum(d.AmountContributed) as amount
        FROM organizations o
        JOIN donors d ON d.donororganization = o.id
        GROUP BY o.id
    ) AS t
    UNION ALL
    (
        SELECT o.id as id, sum(s.AmountRaised) as amount
        FROM organizations o
        JOIN student s ON s.orgid = o.id
        GROUP BY o.id
    ) AS t
) as t
GROUP BY o.id;

答案 1 :(得分:0)

我倾向于这样做:

select orgid, sum(AmountRaised) as AmountRaised, sum(AmountDonated) as AmountDonated,
       (sum(AmountRaised) + sum(AmountDonated)) as total
from ((select s.orgid, AmountRaised, 0 as AmountDonated
       from student s
      ) union all
      (select d.orgid, 0 as AmountRaised, AmountDonated
       from donors d
      )
     ) o
group by orgid;

您可以使用额外的join来引入有关组织的其他数据。