2013-05-12 53 views
2

我遇到問題。PHP - 回聲缺失條目

我有三個表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列:根據學生實際

數量

這裏的目標是查詢將回應PE和社會研究的最後2個主題,以便我可以將它們插入到class_tbl中。回聲告訴我,在這個學期和學年,我沒有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個人失蹤科目 「體育與社會研究」。

+0

請構建多一點人類可讀(例如使事情粗體或斜體) – kelunik 2013-05-12 08:57:01

+0

,如果您使用HTTP:// sqlfiddle .com /,然後幫助你會很容易 – 2013-05-12 09:02:48

回答

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   ║ 
╚════════════╩════════════════╩════════════╩═════════════╝ 
+0

許多tnx你...最後一個問題。請問是否可以,SELECT和class_tbl「b」代表「a。*」是什麼意思?他們應該是桌子嗎? Sory ... – reggel 2013-05-12 09:55:54

+0

'a和b'分別被稱爲表'subject_tbl'和'class_tbl'的別名。 'a。*'表示選擇表'subject_tbl'中的所有列。 – 2013-05-12 09:58:44

+0

wow tnx隊友,我之前從未使用過別名表... – reggel 2013-05-12 10:05:41