[英]Left join is not working fine
表tbl_students
Student_pid name email
1 waheed waheed@gmail.com
2 fareed fareed@gmail.com
表r_job_invitations
id_job email
101 waheed@gmail.com
101 fareed@gmail.com
123 waheed@gmail.com
123 fareed@gmail.com
表r_job_groups
student_id job_id group_id
1 101 1
2 101 2
1 123 1
2 123 2
從上面的三個表中,我試圖讓學生有條件。 這是我的查詢:
$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個學生。
我該如何解決這個問題?
在選擇中使用var時要小心,您可能會受到sql注入的影響
無論如何,您可以使用distinct來避免重復值
$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 );
或使用不同的動態表
$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 );
邀請表似乎完全沒有必要-以及重復的原因。 將查詢寫為:
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
。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.