左连接工作不正常

时间:2017-01-21 12:17:15

标签: mysql sql

表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

从上面的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名学生。 我该如何解决这个问题呢?

3 个答案:

答案 0 :(得分:1)

在你的选择中使用vars时要小心,你可以将它们用于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 );

或使用独特的dinamic table

  $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 );

lloking你的数据样本也尝试改变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 );

答案 1 :(得分:1)

邀请表似乎完全没必要 - 以及重复的原因。将查询写为:

JOIN

我还怀疑你想要LEFT JOIN而不是while

答案 2 :(得分: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