2017-01-21 112 views
1

表tbl_studentsLEFT JOIN工作不細

Student_pid  name    email 
1    waheed    [email protected] 
2    fareed    [email protected] 

表r_job_invitations

id_job email 
101  [email protected] 
101  [email protected] 
123  [email protected] 
123  [email protected] 

表r_job_groups

student_id job_id group_id 
1    101  1 
2    101  2 
1    123  1 
2    123  2 

從以上3代表我試圖讓學生有一個條件。這是我的查詢:

$studentQuery = $conn->query("SELECT 
     s.student_pid,jbi.test_status 
     FROM `r_job_groups` jtg 
     LEFT JOIN tbl_students s ON jtg.student_id=s.student_pid 
     LEFT JOIN r_job_invitations jbi ON jbi.email=s.student_email 
     where jtg.group_id=".$group." and job_id=".$jobID); 

從上面的查詢,爲

$group = 1 and $jobID = 101 

結果的值來了是這樣的:

student_pid 
1 
1 
2 
2 

實際結果應該是這樣的:

student_pid 
    1 
    2 

我的問題是我收到的學生多布爾時間

按查詢時,結果應該給2名學生,但它產生的,因爲作業ID的4名學生沒有工作正常連接。
我該如何解決這個問題?

回答

1

小心在你選擇使用瓦爾你可以subsject到SQL注入

反正你可以使用不同的避免重複值

$studentQuery = $conn->query("SELECT DISCINCT 
    s.student_pid 
    FROM `r_job_groups` jtg 
    LEFT JOIN tbl_students s ON jtg.student_id=s.student_pid 
    LEFT JOIN r_job_invitations jbi ON jbi.email=s.student_email 
    where jtg.group_id=".$group." and jtg job_id=".$jobID); 

,或者使用不同的DINAMIC表

$studentQuery = $conn->query("SELECT 
    s.student_pid 
    FROM `r_job_groups` jtg 
    LEFT JOIN (select distinct student_pid 
      from tbl_students) s ON jtg.student_id=s.student_pid 
    LEFT JOIN r_job_invitations jbi ON jbi.email=s.student_email 
    where jtg.group_id=".$group." and jtg.job_id=".$jobID); 

並找到您的數據樣本也嘗試更改joi表的順序

$studentQuery = $conn->query("SELECT DISTINCT s.student_pid 
     FROM tbl_students s 
     LEFT `r_job_groups` jtg s ON jtg.student_id=s.student_pid 
     LEFT JOIN r_job_invitations jbi ON jbi.email=s.student_email 
    where jtg.group_id=".$group." and job_id=".$jobID); 
+0

@AbdulWaheed請問這是job_id的表nme嗎? ...任何方式的分析應用在結果不是在哪裏條件.. – scaisEdge

+0

不清楚我爲什麼你不使用不同的..根據你的結果你應該使用這個條款,因爲(我重複自己)的子句應用於結果並且不涉及行過濾器(where子句) – scaisEdge

+0

@AbdulWaheed。我有更新答案..讓我知道 – scaisEdge

1

邀請表似乎完全沒有必要 - 並且是重複的原因。編寫查詢爲:

SELECT s.student_pid 
FROM `r_job_groups` jtg LEFT JOIN 
     tbl_students s 
     ON jtg.student_id = s.student_pid 
WHERE jtg.group_id = ".$group." and jtg.job_id = ".$jobID; 

我也懷疑你想JOIN而不是LEFT JOIN

+0

需要邀請表對我來說,檢查一次更新的問題。 @Gordon –

0
SELECT jbi.*, s.student_pid,jbi.test_status FROM 
`r_job_groups` jtg LEFT JOIN tbl_students s ON jtg.student_id=s.student_pid 
LEFT JOIN r_job_invitations jbi ON jbi.email=s.student_email 
where jtg.group_id=1 and jtg.job_id=109 and jtg.job_id=jbi.id_job