MySQL选择与左连接不同?

时间:2016-07-11 16:45:05

标签: mysql sql select left-join distinct

我正在尝试获取没有公司级笔记的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)
        )
    );

2 个答案:

答案 0 :(得分:2)

最简单的思考方法是首先找到所有拥有公司级别笔记的公司,您可以使用

 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);

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

答案 1 :(得分:0)

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;