我有一个问题。
我有三个表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 中。 echo 告诉我,在该学期和学年中,我没有 2 个科目的 2 个条目。该查询不会回显 class_tbl 条目中已有的科目,即数学、科学和历史。 如何查询和回显该学期、该年缺失的科目?我实在想不出什么主意。帮助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 个科目“体育和社会研究”。
最佳答案
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 ║
╚════════════╩════════════════╩════════════╩═════════════╝
关于PHP - 回显缺少的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16505698/