2012-10-14 65 views
3

其他專欄中,我有兩個表MySQL的 - 在一個表中一列的總和與其他表

表1是

idno   marks 
    1    12 
    1    13 
    1    22 
    2    32 
    2    35 
    2    11 and so on 

表2是

idno   marks 
    1    16 
    1    22 
    1    21 
    2    35 
    2    16 
    2    22 and so on 

我提供一個形式用戶輸入IDNO並提交

如果用戶在表單中輸入「1」並提交,則輸出應爲

 Total Marks 
      106 

即IDNO 1的所有標記的表1 +總和IDNO 1的所有標記的在表2的總和

(12 + 13 + 22)+(16 + 22 + 21)= 106

,我使用下面的代碼

<form id="form" action="sum.php" method="post"> 
<td><p align="center"> IDNO : <input type="text" name="id" id="id" maxlength="10"></p></td> 
<input type="submit" id="submit" class='btnExample' value="Click here to get your Result" 
</form> 

<?PHP 
$user_name = "admin"; 
$password = "123456"; 
$database = "demo"; 
$server = "localhost"; 
$db_handle = mysql_connect($server, $user_name, $password); 
$db_found = mysql_select_db($database, $db_handle); 

if ($db_found) { 
$id = mysql_real_escape_string($_POST['id']); 
$add = "SELECT htno, SUM(tech) 
FROM(SELECT htno, SUM(tm) AS tech FROM jbit WHERE htno='$id' 
UNION ALL 
SELECT htno, SUM(tm1) AS tech FROM hmm WHERE htno='$id') AS tech4 "; 
$result3 = mysql_query($add); 
echo " 
<center><table id='mytable' cellspacing='0' border=3 align=center> 
<tr> 
<TH scope='col'>Total Marks</TH> 
</tr><center>"; 
while ($row1 = mysql_fetch_assoc($result3)){ 
echo "<tr>"; 
echo "<td align=center>" . $row1['tech4']. "</td>"; 
echo "</tr>"; 
} 
mysql_close($db_handle); 
else { 
print "Database NOT Found "; 
mysql_close($db_handle); 
} 

但輸出是空白

請幫我

+0

嘗試'SUM(TM)AS tech1','SUM(TM1)AS tech2',然後'總和(tech1 + TECH2)' – GBD

+0

無它不工作frnd @GBD – Aryan

+0

在mysql_query之後echo mysql_error() – GBD

回答

1

您好像缺少GROUP by htno在WHERE子句之後的兩個部分聯合。或者你可以考慮從工會的SELECT子句中刪除htno字段。

select sum(sm) from 
    (select Sum(marks) sm from sums1 where idno=1 
    union 
    select Sum(marks) sm from sums2 where idno=1) ss 

測試這對MySQL和它的作品

+0

添加後,輸出爲空白否更改frnd @Ertunc – Aryan

+0

您是否在Web瀏覽器中檢查頁面的源代碼?你可以添加死亡;在PHP中在指定的點崩潰的應用程序。也許你的腳本壞了,不會輸出任何結果。 –

+0

沒有我在那個頁面中執行完美的其他查詢,只有這個查詢沒有顯示任何輸出 – Aryan

1
WHERE htno='$id) AS tech4 "; 
       ^----here is the problem should be htno='$id' 
+0

編輯好的朋友問題 - 請告訴我解決方案@NullPointer – Aryan

0
SELECT SUM(tech) AS tech4 FROM (
(SELECT SUM(tm) AS tech FROM jbit WHERE htno='$id') 
UNION ALL 
(SELECT SUM(tm) AS tech FROM hmm WHERE htno='$id') 
) t1 
相關問題