微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

where 子句中外部联接表的列上的可选过滤器

如何解决where 子句中外部联接表的列上的可选过滤器

我有两张桌子:

create table student
(
    studentid       bigint primary key not null,name            varchar(200)        not null
);

create table courseregistration
(
    studentid       bigint not null,coursenamename  varchar(200) not null,isfinished        boolean default false
); 

--insert some data
insert into student values(1,'Dave');
insert into courseregistration values(1,'sql',true);

Student 是通过 id 获取的,所以它应该总是在结果中返回。 courseregistration 中的条目是可选的,如果有匹配的行,则应返回,并且应根据 isfinished=false 过滤那些匹配的行。这意味着我想获得尚未完成的课程注册。尝试将 studentcourseregistration 外连接,并在 courseregistration 上过滤 isfinished=false。请注意,我仍然想检索学生。

尝试此操作不返回任何行:

select * from student
left outer join courseregistration using(studentid)
where studentid = 1
and courseregistration.isfinished = false

在上面的示例中,我想要的是具有 1 行学生的结果集,但课程行为空(因为唯一的示例具有 isfinished=true)。不过还有一个限制。如果 courseregistration 中没有对应的行,则应该仍然有学生条目的结果。

这是一个调整后的例子。我可以调整我的代码解决这个问题,但我真的想知道,在 postgresql解决这个问题的“正确/聪明的方法”是什么?


PS 我之前在 Oracle 中使用过 (+)解决类似问题。

解决方法

这不是你要找的吗:

select * from student s
left outer join courseregistration  cr
   on s.studentid = cr.studentid
   and cr.isfinished = false
where s.studentid = 1

dbfiddle here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。