如何通过总和在表中显示2tabile数据

时间:2014-12-26 10:13:25

标签: php mysql

我想显示从2个表到1个表的一些数据。和1个表的列将作为学生ID加上。

最后所有数据都会显示为学生ID 请看这个图像以清楚我的问题。 PLS帮助。

enter image description here

<?php

$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="workshop_all"; // Database name


// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

?>


<?php


$sqlnew="SELECT std_id, sum(pay) AS pay FROM payment GROUP BY std_id";
$resultnew=mysql_query($sqlnew);



?>






<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<table width="400" border="1" cellspacing="0" cellpadding="3">
<tr>
<td colspan="6"><div align="center"><strong>List data from mysql </strong> </div></td>
</tr>

<tr>

<td align="center"><strong>std id</strong></td>

<td align="center"><strong>Email</strong></td>
<td align="center"><strong>pay</strong></td>




<tr>
<?php
while($rows=mysql_fetch_array($resultnew))  {
?>

<td><?php echo $rows['std_id']; ?></td>
<td><?php echo $rows['email']; ?></td>
<td><?php echo $rows['pay']; ?></td>



</tr>

<?php
}

?>



</table>
</td>
</tr>
</table>




<?php
mysql_close();
?>

3 个答案:

答案 0 :(得分:0)

只需使用像这样的加入:

SELECT t1.id, t1.email, sum(t2.pay) as pay FROMTable1 t1 JOIN Table2 t2 on t1.id = t2. std_id
GROUP BY t1.id, t2.email

答案 1 :(得分:0)

在下面的查询中使用了联接

//change TABLE1 TO your table name

$sqlnew="SELECT p.std_id, sum(p.pay) AS pay,t1.email FROM payment p LEFT JOIN TABLE1 as t1 ON(t1.id=p.std_id) GROUP BY p.std_id";
$resultnew=mysql_query($sqlnew);

根据您的要求更改联接类型。以上查询仅用于示例

  • INNER JOIN:当BOTH中至少有一个匹配时返回所有行 表

  • LEFT JOIN:返回左表中的所有行以及匹配的行 从右表

  • RIGHT JOIN:返回右表中的所有行,并匹配 左表中的行

  • FULL JOIN:当其中一个表中有匹配时返回所有行

有关加入click here 的详情 并检查此http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/

答案 2 :(得分:0)

select t2.std_id, t1.email, sum(t2.pay) as pay  
from table1 t1, table2 t2 where t1.id = t2.std_id group by t2.std_id