MySql左外连接条件

时间:2014-01-26 13:26:51

标签: mysql sql database subquery left-join

我有两张桌子

    student_info(id,mobile,cTId,lvDate)

    term_marks(tmId,stdId,cTId,marks,year)

现在我想根据其他检查找出所有不存在term_marks的学生ID, 所以我使用这个查询,但它返回所有匹配的,不匹配的两个表

     $sql = "select * from student_info si LEFT OUTER JOIN term_marks tm ON si.id=tm.stdId and si.cTId=tm.cTId AND tm.year=$year)
WHERE si.cTId=$cTId and si.lvDate=0";

我也试过了

      $sql = "select * from student_info si left outer JOIN term_marks tm where si.id=tm.stdId 
     and si.cTId=tm.cTId and si.cTId=$cTId and tm.year=$year and si.lvDate=0";  

你能帮助我吗?

1 个答案:

答案 0 :(得分:2)

SELECT si.* 
FROM student_info si 
WHERE si.cTId = $cTId 
  AND si.lvDate = 0
  AND si.id NOT IN 
  ( 
    SELECT tm.stdId 
    FROM term_marks tm 
    WHERE tm.year = $year
  )