我有3张桌子:
表a => id,name
表b => id,id_a,金额
表c => id,id_a,金额
如何从表b和表c?
中选择表a和总金额我已经尝试过了:
SELECT a.`name`, SUM(b.`amount`) AS Total
FROM a
LEFT JOIN b ON a.`id` = b.`id_a`
UNION
SELECT a.`name`, SUM(c.`amount`) AS Total
FROM a
RIGHT JOIN c ON a.`id` = c.`id_a`
GROUP BY a.`id`
但它显示了表a中的多个记录,其中表b和表c中都有id_a值。
仅供参考:如果插入表a,则表b或表c或表b和表c都将插入详细信息。因此,表a或表b中没有可能的表a没有详细信息
这是示例数据
表格a:
id | name
1 | name 1
2 | name 2
表格b:
id | id_a | amount
1 | 1 | 300
2 | 1 | 200
表格c:
id | id_a | amount
1 | 1 | 200
2 | 1 | 100
3 | 2 | 300
4 | 2 | 100
首选结果:
name | amount
name 1 | 800
name 2 | 400
更新答案=>感谢@Jens
SELECT d.NAME, SUM(d.Total) FROM (
SELECT a.id AS id , a.`name` AS NAME, SUM(b.`amount`) AS Total
FROM a
LEFT JOIN b ON a.`id` = b.`id_a`
GROUP BY a.`id`
UNION
SELECT a.`id` AS id, a.`name`, SUM(c.`amount`) AS Total
FROM a
RIGHT JOIN c ON a.`id` = c.`id_a`
GROUP BY a.`id`
) AS d
GROUP BY d.`id`
来自@Alex的另一个回答是工作和简单 感谢@Jens和@Alex。这增加了我的知识
答案 0 :(得分:1)
尝试
select d.name, sum(d.total) from (
SELECT a.id as id , a.`name` as name, b.`amount` AS Total
FROM a
LEFT JOIN b ON a.`id` = b.`id_a`
UNION
SELECT a.id as id a.`name`, c.`amount` AS Total
FROM a
RIGHT JOIN c ON a.`id` = c.`id_a`
) as d
GROUP BY d.`id`
<强>更新:强>
SELECT d.NAME, SUM(d.Total) FROM (
SELECT a.id AS id , a.`name` AS NAME, SUM(b.`amount`) AS Total
FROM a
LEFT JOIN b ON a.`id` = b.`id_a`
GROUP BY a.`id`
UNION
SELECT a.`id` AS id, a.`name`, SUM(c.`amount`) AS Total
FROM a
RIGHT JOIN c ON a.`id` = c.`id_a`
GROUP BY a.`id`
) AS d
GROUP BY d.`id`
答案 1 :(得分:0)
你试过这个吗?
SELECT a.name, sum(b.amount), sum(c.amount)
FROM a
JOIN b on a.id = b.id_a
JOIN c on a.id = c.id_a
GROUP BY a.id
不确定关系,但如果你的情况如此,你可以用LEFT JOIN替换JOIN。
<强>更新强>
这应该有效:
SELECT a.name as "name", sum(d.amount) as "amount"
FROM a
JOIN (SELECT id_a, amount FROM b UNION ALL SELECT id_a, amount FROM c) as d
on d.id_a = a.id
group by a.name
这会产生以下结果:
name1 | 800
name2 | 400