我想在where子句中放置一个case条件,即如果第二个表的semester column
为null,我需要过滤semester is null
所在的列。如果没有,我需要在另一个条件下过滤数据。
// 如果学期为null,我需要查询如下:
select * from tbl_courses tc
left join tbl_exams te on tc.courseID = te.courseID
where te.gradeID=10 and
te.semester is null
// 如果学期不为null,则查询应为
select * from tbl_courses tc
left join tbl_exams te on tc.courseID = te.courseID
where te.gradeID=10 and
te.semester is null
对于此要求,我如何从sql本身编写单个查询,如下所示:
select * from tbl_courses tc
left join tbl_exams te on tc.courseID = te.courseID
where te.gradeID=10 and
(case when te.semester is null
then te.semester is null
else te.semester = tc.semester END)
任何方式这都不对。请帮助我
答案 0 :(得分:2)
假设你的第二个选择陈述应该是:
select * from tbl_courses tc
left join tbl_exams te on tc.courseID = te.courseID
where te.gradeID=10
and te.semester = tc.semester
试试这个:
select *
from tbl_courses tc
left join tbl_exams te on tc.courseID = te.courseID
where te.gradeID=10
and (
te.semester = tc.semester
OR te.semester is null
)