[英]MySQL Select Distinct with Left Join?
I am trying to get a list of company_id
's that have no company-level notes. 我想获得一个没有公司级笔记的company_id
列表。 The company may, however, have location-level notes. 但是,该公司可能有位置级别的说明。
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
I would want my result table to be this: 我希望我的结果表是这样的:
company_id name
1 Foo
3 Baz
Update 更新
Foo
/ company_id = 1
does not have a company-level note because the note also has a location_id
, which makes it a location-level note. Foo
/ company_id = 1
没有公司级别的注释,因为该注释还具有location_id
,这使其成为位置级别注释。 Company-level notes are notes that only link to a company (and not a location). 公司级别的票据是仅链接到公司(而非位置)的票据。
End of Update 更新结束
I've tried doing something like this, but it returns an empty set, so I'm not sure if it's working and there aren't any companies without company-level notes or if I'm doing something wrong. 我已经尝试过做这样的事情,但是它返回一个空集,所以我不确定它是否有效,并且没有任何公司没有公司级别的注释或者我做错了什么。
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)
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)
)
);
The easiest way to think about this is to first find the all the companies that have company level notes, which you can do with 考虑这一点的最简单方法是首先找到所有具有公司级别备注的公司,您可以这样做
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;
Then simply remove these companies from the company select: 然后只需从公司中删除这些公司选择:
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);
*Updated to use inner join instead of comma-separated join. *已更新以使用内部联接而不是逗号分隔的联接。
SELECT DISTINCT c.*
FROM company c
LEFT
JOIN note n
ON n.company_id = c.company_id
AND n.location_id IS NULL
WHERE n.note_id IS NULL;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.