gpt4 book ai didi

php - MySql 连接查询左连接

转载 作者:行者123 更新时间:2023-11-29 04:01:34 24 4
gpt4 key购买 nike

我有表名 students 具有字段 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

这对我来说很好..

现在我也想从 houses 表中获取房屋名称

我试过这个查询

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

它给了我 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

关于php - MySql 连接查询左连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15470114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com