我正在寻找一种更有效的方法来构建这个查询(双子查询让我感到畏缩):
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
我现有查询的逻辑如下:
它有效 - 它有点难看。
答案 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