3

我有两张桌子

表 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 

即表1中Idno 1的所有分数之和+表2中Idno 1的所有分数之和

(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);
}

但输出为空白

请帮帮我

4

3 回答 3

1
WHERE htno='$id) AS tech4 "; 
               ^----here is the problem  should be htno='$id'
于 2012-10-14T17:48:07.793 回答
1

在 WHERE 子句之后,您似乎在联合的两个部分都缺少GROUP by htno 。或者您可以考虑从联合的 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 上测试过,它可以工作

于 2012-10-14T17:55:25.083 回答
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
于 2012-10-14T20:27:38.293 回答