MySql Join Query左连接

时间:2013-03-18 05:08:28

标签: php mysql sql

我的表名学生的字段为 student_id,house_id 等。 和科目,房屋,学生主题

我正在使用此查询

SELECT students_subjects.student_id,students.house_id,students_subjects.subject_id,subjects.subject_name,students.rollno,students.first_name, students.last_name FROM 
students_subjects LEFT JOIN students on students_subjects.student_id=students.id
LEFT JOIN subjects on students_subjects.subject_id=subjects.id  WHERE students_subjects.class_years_section_id=1 

这对我来说很好..

现在我想从房子表中得到房子名称

我试过了这个查询

SELECT students_subjects.student_id,students.house_id,houses.house_name, students_subjects.subject_id,subjects.subject_name,students.rollno,students.first_name, students.last_name FROM 
students_subjects LEFT JOIN students on students_subjects.student_id=students.id
LEFT JOIN subjects on students_subjects.subject_id=subjects.id 

LEFT JOIN在students.house_id = houses.id上  在哪里students_subjects.class_years_section_id = 1

AND students_subjects.school_session_id=1 AND students.is_active=1

它给了我house_name = NULL

任何人都可以告诉我如何获得房屋名称。使用连接查询

谢谢

2 个答案:

答案 0 :(得分:7)

查询中的错误是由LEFT JOIN子句之后的WHERE关键字引起的,

SELECT  students_subjects.student_id,
        students.house_id,
        students_subjects.subject_id,
        subjects.subject_name,
        students.rollno,
        students.first_name, 
        students.last_name 
FROM    students_subjects 
        LEFT JOIN students 
            on students_subjects.student_id=students.id
        LEFT JOIN subjects 
            on students_subjects.subject_id=subjects.id
        LEFT JOIN houses 
            on students.house_id=houses.id
WHERE   students_subjects.class_years_section_id = 1 AND 
        students_subjects.school_session_id = 1 AND 
        students.is_active = 1

请记住,JOINFROM条款的一部分。


更新1

SELECT  b.student_id,
        a.house_id,
        b.subject_id,
        c.subject_name,
        a.rollno,
        a.first_name, 
        a.last_name,
        d.house_name            
FROM    students a
        INNER JOIN students_subjects b
            ON b.student_id = a.id
        INNER JOIN subjects  c
            ON b.subject_id = c.id
        INNER JOIN houses d
            ON a.house_id = d.id
WHERE   b.class_years_section_id = 1 AND 
        b.school_session_id = 1 AND 
        a.is_active = 1

答案 1 :(得分:0)

你错过了WHERE条款,试试这个:

SELECT students_subjects.student_id,students.house_id,students_subjects.subject_id,subjects.subject_name,students.rollno,students.first_name, students.last_name 
FROM students_subjects 
     LEFT JOIN students ON students_subjects.student_id=students.id
     LEFT JOIN subjects ON students_subjects.subject_id=subjects.id  
     LEFT JOIN houses ON students.house_id=houses.id
WHERE students_subjects.class_years_section_id=1 
AND students_subjects.school_session_id=1 AND students.is_active=1