[英]Table referencing itself , MySQL, primary key and foreign key in same table , select statement
[英]How to get the sum of foreign key table as a value in the primary table row in a select statement
如何在select語句的主表行中獲取外鍵表總和作為值?
考慮表1:
id(PK) name description
-----------------------------
1 test1 desc1
2 test2 desc2
表2是:
id(FK) value
-----------------
1 5
1 6
2 7
2 8
SQL select語句的結果應類似於
id name desc sum(value)
----------------------------------
1 test1 desc1 11
select
t.*,
( select
sum(tt.value)
from table2 tt
where tt.id = t.id) sum_value
from table1
HTH
最明顯的方法:
select p.id, p.name, p.description, sum(f.value)
from p join f on f.id = p.id
group by p.id, p.name, p.description
或者,另一種方法是在聯接之前顯式地將子值分組(不確定此語法對於Oracle以外的系統是否正確):
select p.id, p.name, p.description, fgroup.valuesum
from p join (select id,sum(value) valuesum from f group by id) fgroup
on p.id = fgroup.id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.