2013-10-26 70 views
0

場景:MySQL查詢,並添加字段的值(父母,子女)DB結構

我有兩個表(Parent and Child relationship) = (tblreqslip, tblreqdetails)

tblreqslip = column fields (parent_id, client_name, date) 
tblreqdetails = column fields (child_id, parent_id, subtotals) 

需要幫助:

In getting all the values in my child table (field ="subtotals") and add them all up "simple addition Math function".

注:我孩子tblreqdetails字段=(值不同)例如:父母ID =「1」的子字段值爲10個小計字段,父母ID =「2」的子字段值爲15個小計字段。

這裏是我停留在:

$p_id=$_GET['parent_id']; //get from Post URl 
$query = "SELECT * FROM tblreqdetails WHERE child_id='$p_id'"; 
$select = mysql_query($query) or die(mysql_error()); 
$rw = mysql_fetch_array($select); 

(我失去一條線在這裏從「小計」字段得到值,添加它們加起來無論多少都在小計值現場,只是呼應總量) 例如:ID =「1」 $總價值=(200.50 + 1000 + 3000 ....以此類推,直到有多少次全我的孩子表有根據我的父ID的值)

非常感謝。

+0

首先,這是奇怪的,通常你的子查詢是'SELECT * FROM tblreqdetails WHERE PARENT_ID =「$的p_id」「;'或類似的東西......孩子既具有LOCALID和家長的parentID可能只是LOCALID等。 – 2013-10-26 01:46:48

+0

感謝ebyrob。我應該如何糾正呢?從我的子表得到的所有分類彙總,並將它們添加一切? –

+0

對於初學者來說,展現在你的問題中的所有列的兩個表(或至少所有相關列),所以我們可以我想你必須改變列定義,但是我不知道沒有看到表定義,應該有簡單的tblreqslip和tblreqdetails之間的直接關係 – 2013-10-26 01:51:33

回答

0

我假設你有這兩個表:

tblreqslip 
+++++ 
ID + 
+++++ 
    1 | 
    2 | 
    3 | 

tblreqdetails 
++++++++++++++++++++++ 
child_id | subtotals + 
++++++++++++++++++++++ 
    1  | 4500  | 
    1  | 6000  | 
    2  | 3000  | 
    3  | 1500  | 
    3  | 1000  | 

修訂 試試這個,它與我:

$p_id=$_GET['parent_id']; 
$query = "SELECT * FROM tblreqdetails WHERE child_id='$p_id'"; 
$select = mysql_query($query) ; 
$i = 0; 
while ($rw = mysql_fetch_array($select)){ 
$i++; 
$subtotals[$i] = $rw['subtotals']; 
} 
$TOTAL = array_sum($subtotals); // sum all the subtotals field with selected child_id 
echo "id : $p_id total is ".$TOTAL; 

現在,你有分類彙總的總。

+0

OH MY!現在試試這個... :)那麼激動...... –

+0

得到這個錯誤:(「致命錯誤:用盡134217728個字節允許內存大小(試圖分配35個字節)在C:\ XAMPP \ htdocs中\ ADMIN \ preq_content。在線17上的PHP「 –

+0

我認爲你會有一個錯誤..:D –