查询输出的记录多于应有的记录

时间:2011-10-17 14:15:04

标签: php mysql database join

我有很多连接的SQL查询。事实是,在查询必须加入StudentClass表和Class表之前,它输出了正确的行数,应该是4行。但是当我包含Class和StudentClass表时,它应该输出6行,它仍然应该输出4行。问题是,如果一个学生正在学习2个模块并且是2个类,那么它输出4个模块,这2个模块是重复的,4个类是2个类重复的。为什么会发生这种情况,我设置表格的方式有问题还是查询?

以下是PHP代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

  <head>
    <title>Exam Grade Report</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  </head>

  <body>

    <?php
      if (isset($_POST['submit'])) {

        $query = "
          SELECT * FROM Course c
            INNER JOIN CourseModule cm ON c.CourseId = cm.CourseId
            JOIN Module m ON cm.ModuleId = m.ModuleId 
            JOIN Session s ON m.ModuleId = s.ModuleId
            JOIN Grade_Report gr ON s.SessionId = gr.SessionId
            JOIN Student st ON gr.StudentId = st.StudentId
            JOIN StudentClass sc ON st.StudentId = sc.StudentId
            JOIN Class cl ON sc.ClassId = cl.ClassId 
          WHERE
            ('".mysql_real_escape_string($sessionid)."' = '' OR gr.SessionId = '".mysql_real_escape_string($sessionid)."')
          AND
            ('".mysql_real_escape_string($courseid)."' = '' OR cl.CourseId = '".mysql_real_escape_string($courseid)."')
          AND
            ('".mysql_real_escape_string($moduleid)."' = '' OR cl.ModuleId = '".mysql_real_escape_string($moduleid)."')
          AND
            ('".mysql_real_escape_string($classid)."' = '' OR sc.ClassId = '".mysql_real_escape_string($classid)."')
          AND
            ('".mysql_real_escape_string($teacherid)."' = '' OR s.TeacherId = '".mysql_real_escape_string($teacherid)."')
          AND
            ('".mysql_real_escape_string($studentid)."' = '' OR gr.StudentId = '".mysql_real_escape_string($studentid)."')
          AND
            ('".mysql_real_escape_string($grade)."' = '' OR gr.Grade = '".mysql_real_escape_string($grade)."')
          ORDER BY $orderfield ASC";

        $num = mysql_num_rows($result = mysql_query($query));
        mysql_close();

    ?>

  </body>
</html>

我想在word文档中显示查询结果和表格。如何按顺序附加单词文件,以便在需要时可以打开单词文档?

谢谢

1 个答案:

答案 0 :(得分:1)

您是否尝试将所有JOIN更改为LEFT JOIN?