在PostgreSQL中,我有两个表:
company
id名称
owner
company_id已验证
在没有关联company
的情况下,没有owner
记录出现在数据库中。
但是我们有company
记录,在没有owner
的DB中呈现。
如何一次查询选择所有只有验证所有者的公司和没有验证所有者的公司?
我已经尝试了许多查询,但没有人在工作:(
例如,以下查询不起作用:
select count(c.id)
from company as c
left outer join owner o on c.id = o.company_id and o.verified is not null
where not (c.id = o.company_id and o.verified is null);
示例模式
http://sqlfiddle.com/#!17/ab366
create table company (
id int unique,
name varchar(255)
);
create table owner (
first_name varchar(255),
company_id int unique references company(id) on update cascade on delete set null,
verified boolean
);
insert into company values (1, 'company1');
insert into company values (2, 'company2');
insert into company values (3, 'company3');
insert into owner values ('owner1', 1, true);
insert into owner values ('owner2', 2, false);
我需要选择company1
和company3
。
发布于 2019-08-22 05:26:14
在这里,我将实际使用从company
表到owner
表的左连接:
SELECT c.*
FROM company c
LEFT JOIN owner o
ON c.id = o.company_id
WHERE
o.company_id IS NULL OR -- companies without owners
o.verified IS NOT NULL; -- companies with verified owners
发布于 2019-08-22 12:11:29
我将在where
子句中使用过滤:
select c.*
from companies c
where not exists (select 1
from owners o
where o.company_id = c.id and
not o.verified
);
这样做的主要原因是,如果有多个经过验证的所有者,left join
版本可能会返回重复项。
第二个原因是这更紧密地捕捉到了您所描述的逻辑。。。你想要没有未经验证的所有者的公司。
https://stackoverflow.com/questions/57602510
复制