如何从各种表中获取行并执行求和操作?
例如 表1:树
-------------------
id name
-------------------
1 tree1
-------------------
2 tree2
-------------------
3 tree3
-------------------
4 tree4
-------------------
表2: leaf
--------------------------------
tree_id name value
--------------------------------
1 test1 5
--------------------------------
1 test2 3
--------------------------------
2 test3 7
--------------------------------
4 test4 9
--------------------------------
期望的输出:
select tree.id,tree.name,sum(leaf.value) as total from tree,leaf where leaf.tree_id=tree.id
Array([0] => Array([id]=>1, [name]=>tree1, [total]=>8),
[1] => Array([id]=>2, [name]=>tree2, [total]=>7)
[2] => Array([id]=>3, [name]=>tree3, [total]=>0)
[3] => Array([id]=>4, [name]=>tree4, [total]=>9))
答案 0 :(得分:0)
SELECT tree.id, tree.name, sum(leaf.value) as total
FROM tree
LEFT JOIN leaf
ON leaf.tree_id = tree.id
GROUP BY tree.id
答案 1 :(得分:0)
SELECT tree.id, tree.name, sum(leaf.value) as total
FROM tree
left join leaf
ON leaf.tree_id = tree.id group by tree.id