mysql左连接多个表,只有主键作为第一个表的外键

时间:2013-01-27 18:14:15

标签: mysql left-join

TB 1 : user_profile as ur-> id(PK),name (total 4k records all unique)    
TB 2 : user_course_rel as ucr-> id,course_id,year_id,division,user_id(Fk)    
TB 3 : students_attendance_lect as sal-> id,subject_id,date,student_id(Fk)    
student_id(Fk) = user_id(Fk) = id(PK).

我想离开加入TB1并获得属于特定课程,年份,部门以及主题和日期的参加者的所有学生的姓名,而不是参加者,这应该是132个独特的记录。
运行以下查询后,我得到总数(4k记录)

select distinct(ur.id), ur.fname
from user_profile as ur
inner join user_course_rel as ucr
    on ucr.user_id=ur.id
left join students_attendance_lect as sal
    on sal.student_id=ucr.user_id
    and ucr.course_id=1
    and ucr.year_id=1
    and ucr.division=3
    and sal.subject_id=2
    and sal.date='2013-01-21'

1 个答案:

答案 0 :(得分:1)

LEFT JOIN中的几个项目看起来应该在WHERE子句中。我不是100%清楚你的问题是什么,但试试:

select distinct(ur.id), ur.fname
from user_profile as ur
inner join user_course_rel as ucr
    on ucr.user_id=ur.id
left join
    (SELECT sal.student_id, sal.subject_id, sal.date
     FROM students_attendance_lect as sal
     WHERE sal.date='2013-01-21'
     AND sal.subject_id = 2) AS sa
    ON sa.student_id=ucr.user_id
WHERE ucr.course_id=1
    and ucr.year_id=1
    and ucr.division=3

你编写它的方式是要求DB在任何一个课程编号为1,分为3,主题编号为2或日期为“2013-01-21”的行上LEFT JOIN,你知道吗?