2

我有个问题。

我有三个表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

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

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

            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 个缺失的科目“体育和社会研究”。

4

1 回答 1

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         ║
╚════════════╩════════════════╩════════════╩═════════════╝
于 2013-05-12T09:06:42.990 回答