2014-01-16 64 views
0

如何從各個表中獲取行並執行求和操作?如何從mysql中的多個表中提取值?

對於實施例 表1:

------------------- 
id  name  
------------------- 
1   tree1  
------------------- 
2   tree2  
------------------- 
3   tree3  
------------------- 
4   tree4  
------------------- 

表2:

-------------------------------- 
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

看看JOIN,INNER JOIN,OUTER JOIN,LEFT JOIN,RIGHT JOIN和CROSS JOIN –

回答

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 
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 
相關問題