gpt4 book ai didi

sql - 在一个查询中使用 JOIN 和条件以及不使用 JOIN 的 SELECT

转载 作者:行者123 更新时间:2023-11-29 14:08:18 25 4
gpt4 key购买 nike

在 PostgreSQL 中我有两个表:

公司ID姓名

所有者公司编号验证

没有 owner 记录,在没有关联 company 的 DB 中显示。

但是我们有 公司 记录,在没有 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);

我需要选择company1company3

最佳答案

我实际上会在这里使用从 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

关于sql - 在一个查询中使用 JOIN 和条件以及不使用 JOIN 的 SELECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57602510/

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