1

我的表名学生 有字段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 

在students.house_id=houses.id 上LEFT JOIN 房屋,其中students_subjects.class_years_section_id=1

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

它给了我 house_name = NULL

谁能告诉我如何获得房屋名称。使用连接查询

谢谢

4

2 回答 2

7

查询中的错误是由LEFT JOINafterWHERE子句的关键字引起的,

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

请记住,JOINs 是FROM条款的一部分。


更新 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
于 2013-03-18T05:10:28.267 回答
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
于 2013-03-18T05:14:16.530 回答