简体   繁体   English

左外部联接,从左查找所有没有出现在右表,mysql

[英]Left outer join, find all from left having no occurrences in right table, mysql

Having two tables, a mapping and a data table, I want to find all mappings that don't have any associated data 有两个表,一个映射和一个数据表,我想查找所有没有任何关联数据的映射

For example: 例如:

     map                 data
============        ===============
mapId | name         mapId | value
------------        ---------------
  1      A             1       x
  2      B             1       y
  3      C             2       z

For this case I want to return the mapId 3/C, since it exists in the map table but does not have a record in the data table 对于这种情况,我想返回mapId 3 / C,因为它存在于映射表中,但在数据表中没有记录

How can I query this? 我该如何查询? I've tried every combo of group and having and where I can think of, the closest I got was 我已经尝试了每个组的组合,并且在想想的地方,我得到的最接近的是

SELECT map.name
FROM map
LEFT OUTER JOIN data on data.mapId = map.mapId
GROUP BY data.mapId
HAVING max(data.value) is null

I also tried grouping by map.mapId, and having count(data.dataId) = 0, all to no avail. 我也尝试通过map.mapId进行分组,并让count(data.dataId)= 0,但都无济于事。 NO matter how I set it up I'm getting either some maps that do have data, or not getting some maps that don't have data. 无论我如何设置,我都会得到一些确实有数据的地图,或者得不到一些没有数据的地图。

No need to group, a left join is enough: 无需分组,左联接就足够了:

SELECT map.*
FROM map LEFT JOIN data 
on data.mapId = map.mapId
WHERE data.mapId is null

Also another way to do it with NOT EXISTS : 另一种使用NOT EXISTS做到这一点的方法:

SELECT map.*
FROM map  
WHERE NOT EXISTS (
  SELECT 1 FROM data 
  WHERE data.mapId = map.mapId
)

You don't need to group by to achieve this. 您无需group by即可实现这一目标。 There can be multiple rows for one mapId in data do I added distinct . 可以有一个多行mapId数据我添加distinct

select
    distinct m.mapId, m.name
from map m
left join data d
    on m.mapId = d.mapId
where d.mapId is null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM