例如,想象一下一对多的关系:
Mail: subject, date etc
Recipient: address在不使用子选择:所有由abc@domain.com接收到的没有来自同一域@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') 发布于 2011-01-17 14:35:45
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'发布于 2011-01-17 15:06:51
我不确定这是否比你的原版更好!--它仍然有一个子选择--但允许域名不是字面上的'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.pkmhth,R
https://stackoverflow.com/questions/4714279
复制相似问题