簡體   English   中英

MySql Join查詢左聯接

[英]MySql Join Query left join

我有表格名稱的學生,其字段為student_id,house_id等。以及主題,房屋,students_subjects

我正在使用此查詢

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上的房屋WHERE students_subjects.class_years_section_id = 1

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

它給了我house_name = NULL

有人能告訴我如何獲得房屋名稱嗎? 使用聯接查詢

謝謝

您的查詢錯誤是由WHERE子句后面的LEFT JOIN關鍵字引起的,

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

您已經錯過了放置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

暫無
暫無

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

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