检索相关表中的所有值为空的记录

时间:2012-01-28 16:58:59

标签: mysql

我正在寻找一种更有效的方法来构建这个查询(双子查询让我感到畏缩):

SELECT contact_id FROM (
  SELECT * FROM (
    SELECT mr.contact_id, di.district
    FROM recipients mr
    JOIN address a ON mr.contact_id = a.contact_id
    JOIN district_values di ON a.id = di.entity_id
    WHERE mr.mid = 29
    ORDER BY di.district DESC ) addrSingle
  GROUP BY mr.contact_id ) addrNull
WHERE di.district IS NULL

让我解释一下这里发生了什么。

收件人拥有联系人列表。每个联系人可能有多个地址。每个地址都有一个相关的district_values表。我需要检索所有地址的district_values.district列为空的联系人。

例如:

Contact A
Address 1.district = 4
Address 2.district = null
= don't include

Contact B
Address 1.district = null
= include

Contact C
Address 1.district = null
Address 2.district = 3
= don't include

我现有查询的逻辑如下:

  1. 检索与相关地址和地区的联系人,以便首先订购任何非空值的地址
  2. 申请分组,因此我减少到一个联系人记录,如果地区的地址被保留
  3. 应用where子句删除至少有一个地区值的地址
  4. 它有效 - 它有点难看。

1 个答案:

答案 0 :(得分:2)

你可以尝试这个,使用LEFT JOIN并计算零的相关记录。

SELECT mr.contact_id 
    FROM recipients mr 
LEFT JOIN address a ON mr.contact_id = a.contact_id  
LEFT JOIN district_values di ON a.id = di.entity_id 
    WHERE mr.mid = 29 
GROUP BY mr.contact_id
    HAVING COUNT(a.*) = 0 AND COUNT(di.*) = 0