[英]MySQL: Join 3 tables with distinct values
So I have 3 tables: tableA, tableB, tableC with structures as follows所以我有 3 个表:tableA、tableB、tableC,其结构如下
tableA表A
id ID | name姓名 | state状态 |
---|---|---|
1 1 | Ray射线 | MD医学博士 |
2 2 | Sam山姆 | LA洛杉矶 |
3 3 | John约翰 | NY纽约 |
tableB表B
id ID | a_id援助 | amount数量 | code代码 |
---|---|---|---|
1 1 | 2 2 | 10 10 | CHARGE收费 |
2 2 | 2 2 | 20 20 | CHARGE收费 |
3 3 | 3 3 | 70 70 | CHARGE收费 |
tableC表C
id ID | a_id援助 | amount数量 | code代码 |
---|---|---|---|
1 1 | 2 2 | 50 50 | CHARGE收费 |
2 2 | 2 2 | 40 40 | DEPOSIT订金 |
3 3 | 1 1 | 60 60 | CHARGE收费 |
I need the output of the join as follows:我需要连接的输出如下:
A id援助 | amount数量 |
---|---|
1 1 | 60 60 |
2 2 | 30 30 |
3 3 | 70 70 |
So, here it calculates the sum of amount based on id in tableA.因此,这里它根据 tableA 中的 id 计算金额的总和。 It checks the tableB for amount and if not present only then it checks tableC.它检查 tableB 的金额,如果不存在,则只检查 tableC。 Thats why the id 2 has amount 30 in output.这就是 id 2 在输出中的数量为 30 的原因。
But what actually happens is the sum of both tables are added.但实际发生的是两个表的总和相加。 So I get amount 120 for id 2. How do I get the required output?所以我得到 120 的 id 2。我如何获得所需的输出?
So I tried this query here所以我在这里尝试了这个查询
Select if( SUM(CASE WHEN B.code != 'DEPOSIT'
THEN B.amount
ELSE 0 END) > 0,
SUM(CASE WHEN B.code != 'DEPOSIT'
THEN B.amount
ELSE 0 END),
SUM(CASE WHEN C.code != 'DEPOSIT'
THEN C.amount
ELSE 0 END)) as total
FROM tableA as A
left join tableB AS B on A.id=B.a_id
LEFT JOIN tableC AS C on A.id=C.a_id
GROUP BY A.id
You can try a solution like this您可以尝试这样的解决方案
Select A.id, SUM(if(B.amount is NOT NULL,B.amount, C.amount)) as total
FROM tableA as A
LEFT JOIN tableB AS B on A.id=B.a_id and B.code != 'DEPOSIT'
LEFT JOIN tableC AS C on A.id=C.a_id and C.code != 'DEPOSIT'
GROUP BY A.id
Test this:测试这个:
SELECT id, CASE WHEN b.amount
THEN b.amount
ELSE c.amount
END amount
FROM tableA a
LEFT JOIN ( SELECT a_id id,
SUM( CASE WHEN code != 'DEPOSIT'
THEN amount
ELSE 0
END ) amount
FROM tableB
GROUP BY id ) b USING (id)
LEFT JOIN ( SELECT a_id id,
SUM( CASE WHEN code != 'DEPOSIT'
THEN amount
ELSE 0
END ) amount
FROM tableC
GROUP BY id ) c USING (id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.