PHP - 回显丢失的条目

时间:2013-05-12 08:54:02

标签: php mysql duplicates

我有一个问题。

我有三个表 class_tbl,subject_tbl和* student_tbl 。 class_tbl有3列*“class_id,subject_id和student_id”。*而subject_tbl有4列*“subject_id,subject_name,subject_yr,subject_sem”*最后* student_tbl有2列“student_id和student_name”。*

class_tbl包含以下行:

**[class_id || subject_id || student_id]**

|| 1001   ||    2002    || 3003

|| 1002   ||    2003    || 3003

|| 1003   ||    2004    || 3003

subject_tbl有5行:

**[subject_id ||  subject_name  || subject_yr || subject_sem]**

|| 2002     ||    Math        ||    2010    || 1st

|| 2003     ||   Science      ||    2010    || 1st

|| 2004     ||    History     ||    2010    || 1st

|| 2005     ||      PE        ||    2010    || 1st

|| 2006     || Social Studies ||    2010    || 1st

student_tbl有1行:具体取决于学生人数

**[student_id || student_name]**

||   3003   ||  John Parker

这里的目标是查询将回显最后2个主题,即PE和社会研究,以便我可以将它们插入到class_tbl中。回声告诉我,在该学期和学年期间,我没有2个科目。查询不会回显已经在class_tbl条目中的主题,即Math,Science和History。 如何查询和回应该学期和一年中缺失的科目?我真的想不出任何想法。帮助tnx!

此处的代码显示该school_yr和学期的所有科目。

            if (isset ($db1)&&$db1!=""){


            }

            <?php

                $student_id = $_POST['student_id'];
                $sem = $_POST['sem'];
                $yr = $_POST['yr'];

                $list = mysql_query("SELECT * 
                                    FROM
                                    class_tbl 
                                    LEFT JOIN
                                    subject_tbl
                                    ON
                                    class_tbl.subject_id = subject_tbl.subject ID
                                    WHERE
                                    student_id = '$student_id'
                                    OR
                                    subject_sem = '$sem' 
                                    OR
                                    subject_yr = '$yr' 
                                    ORDER BY 
                                    subject_id asc");

                while($row_list=mysql_fetch_assoc($list))
                {
                echo $row_list['subject_id'];

                if($row_list['subject_id']==$db1){echo "selected"; }

                echo $row_list['subject_name'];

                }

示例输出为:

你有2个缺席科目“体育与社会研究”。

1 个答案:

答案 0 :(得分:4)

SELECT  a.*
FROM    subject_tbl a
        LEFT JOIN class_tbl b
            ON  a.subject_ID = b.subject_ID AND
                a.subject_yr = 2010 AND
                a.subject_sem = '1st' AND
                b.student_ID = 3003
WHERE   b.subject_ID IS NULL

输出

╔════════════╦════════════════╦════════════╦═════════════╗
║ SUBJECT_ID ║  SUBJECT_NAME  ║ SUBJECT_YR ║ SUBJECT_SEM ║
╠════════════╬════════════════╬════════════╬═════════════╣
║       2005 ║ PE             ║       2010 ║ 1st         ║
║       2006 ║ Social Studies ║       2010 ║ 1st         ║
╚════════════╩════════════════╩════════════╩═════════════╝