【问题标题】:mysql left join with multiple tables,having only primary key as foreign key of first tablemysql左连接多个表,只有主键作为第一个表的外键
【发布时间】:2013-01-27 18:14:14
【问题描述】:
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'

【问题讨论】:

    标签: mysql left-join


    【解决方案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
    

    您编写它的方式是要求数据库在课程 ID 为 1、部门为 3、主题 ID 为 2 或日期为“2013-01-21”的任何行上进行 LEFT JOIN,执行看到了吗?

    【讨论】:

      猜你喜欢
      • 2010-11-20
      • 1970-01-01
      • 1970-01-01
      • 2015-03-13
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2015-03-05
      • 1970-01-01
      相关资源
      最近更新 更多