簡體   English   中英

mysql左連接多個表,只有主鍵作為第一個表的外鍵

[英]mysql left join with multiple tables,having only primary key as foreign key of first table

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'

您的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

您寫的方式是要求數據庫在課程ID為1,除法為3,主題ID為2或日期為'2013-01-21'的任何行上左加入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM