我有4张桌子。
1. Course 2. Semester 3. AssignTeacher 4. Teacher.
Course has id, name, code.
Semester has id, name, course_id.
AssignTeacher has id,course_id,teacher_id.
Teacher has id, name.
现在我想找到courses.code,courses.name,semesters.name和teachers.name 从上表。其中teachers.name应该与AssignTeacher表中具有id的教师一起提供。现在使用课程表,当没有教师ID与该课程而不是显示空值时,我可以设置一些默认值,如'无'在查询?
这是我直到现在写的查询,虽然我没有得到我的预期:
SELECT courses.code, courses.name, semesters.name,teachers.name
FROM semesters
JOIN courses on courses.semester_id = semesters.id
JOIN assign_teachers on assign_teachers.course_id=courses.id
JOIN teachers on assign_teachers.id=teachers.id
答案 0 :(得分:1)
如果我理解正确,请将选择列表更改为
COALESCE(teachers.name, 'None')
答案 1 :(得分:1)
当然,您应该使用COALESCE()
将null替换为所需值:
SELECT courses.code, courses.name, semesters.name,COALESCE(teachers.name,'None') as teacher_name
from semesters join courses on courses.semester_id = semesters.id
join assign_teachers on assign_teachers.course_id=courses.id
join teachers on assign_teachers.id=teachers.id
但是当你没有使用teacher.id时,你得到空值似乎很奇怪。因为你使用普通连接,所以应该过滤这个记录。我认为你应该使用LEFT加入:
SELECT courses.code, courses.name, semesters.name,COALESCE(teachers.name,'None') as teacher_name
from semesters join courses on courses.semester_id = semesters.id
left join assign_teachers on assign_teachers.course_id=courses.id
left join teachers on assign_teachers.id=teachers.id