gpt4 book ai didi

MySQL Select Distinct with Left Join?

转载 作者:可可西里 更新时间:2023-11-01 08:25:08 26 4
gpt4 key购买 nike

我正在尝试获取没有公司级别注释的 company_id 的列表。但是,该公司可能有位置级别的注释。

company
-------------------------
company_id name deleted
1 Foo 0
2 Bar 0
3 Baz 0

location
-----------------------
location_id company_id
6 1
7 2
8 3

note
-----------------------------------------
note_id company_id location_id deleted
10 2 6 0 // location-level note
11 1 7 0 // location-level note
12 null 8 0 // location-level note
13 2 null 0 // company-level note

我希望我的结果表是这样的:

company_id  name
1 Foo
3 Baz

更新

Foo/company_id = 1 没有公司级别的注释,因为该注释还有一个 location_id,这使它成为一个位置级别的注释。公司级注释是仅链接到公司(而不是位置)的注释。

更新结束

我试过这样做,但它返回一个空集,所以我不确定它是否有效,没有任何公司没有公司级别的注释,或者我做错了什么。

SELECT DISTINCT 
c.company_id,
c.name
FROM company AS c
LEFT JOIN note AS n
ON c.company_id = n.company_id
WHERE
c.deleted = 0 AND
n.deleted = 0 AND
n.location_id IS NOT NULL AND
n.location_id != 0 AND
c.company_id = (SELECT MAX(company_id) FROM company)

Mike 修改后的已接受答案

SELECT
company_id,
name
FROM company
WHERE
deleted = 0 AND
company_id NOT IN (
SELECT DISTINCT
c.company_id
FROM company AS c
INNER JOIN note AS n
ON c.company_id = n.company_id
WHERE (
n.deleted = 0 AND
(n.location_id IS NULL OR
n.location_id = 0)
)
);

最佳答案

考虑这个问题的最简单方法是首先找到所有拥有公司级别注释的公司,您可以使用它

 select distinct c.company_id
from company c
inner join notes n
on c.company_id = n.company_id
where n.location_id is null;

然后简单地从公司选择中删除这些公司:

select company_id,
name
from company
where company_id not in (select distinct c.company_id
from company c
inner join notes n
on c.company_id = n.company_id
where n.location_id is null);

*已更新为使用内部联接而不是逗号分隔联接。

关于MySQL Select Distinct with Left Join?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38312120/

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