2012-10-14 33 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 
相关问题