想象一对一对多的关系,例如:
Mail: subject, date etc
Recipient: address
是否可以执行此查询不使用子选择:abc@domain.com收到的所有邮件中没有来自同一域的其他收件人@ domain.com ??
我能找到的唯一方法是使用子选择:
select mail m, recipient r where m.pkm=r.pkm
and (r.address='abc@domain.com')
and not exists (select * from mail ms, recipient rs where m.pkm=ms.pkm and ms.pkm=rs.pkm and rs.address<>'abc@domain.com' and rs.address like '%@domain.com')
答案 0 :(得分:0)
select m.*, r1.*
from mail m
inner join recipient r1 on m.pkm=r1.pkm
left join recipient r2 on m.pkm=r2.pkm and r2.address<>'abc@domain.com' and r2.address like '%@domain.com'
where r2.pkm is null
and r1.address='abc@domain.com'
答案 1 :(得分:0)
我不确定这比你原来的更好! - 它仍然有一个子选择 - 但允许域不是文字'domain.com'。
SELECT m.*
FROM mail m
INNER JOIN
(
SELECT DISTINCT pkm
FROM recipient
GROUP BY pkm, SUBSTRING(email, CHARINDEX('@', email) + 1, 1000)
HAVING COUNT(SUBSTRING(email, CHARINDEX('@', email) + 1, 1000)) = 1
) r
ON m.pkm = r.pkm
hth,R