需要SQL帮助。
表
PersonMsgResponse表的结构
PersonMsgResponse表中的示例行
我需要返回一个没有收到消息的人名列表。
如何将SQL设计为仅返回那些未通过任何方法收到消息的成员的成员名称?
例如,在上面的记录列表中,我的查询应该只返回成员1,因为成员2通过电话接收消息,而成员1没有通过任何一种方法接收消息。
感谢您的帮助。
答案 0 :(得分:2)
您可以通过以下2个内部查询来完成此操作。诀窍是包括所有收到'N'但没有'Y'的人。对于此示例,技术上不需要消息表。
SELECT p.Name
FROM Person p
WHERE p.id IN (
SELECT personID
FROM PersonMsgResponse pmr
WHERE pmr.received = 'N' AND pmr.personID NOT IN (SELECT personID FROM PersonMsgResponse pmr WHERE pmr.received = 'Y')
)
返回
Name
person 1
答案 1 :(得分:1)
您可以使用NOT EXISTS
:
SELECT Id, Name
FROM Person AS p
WHERE NOT EXISTS (SELECT 1
FROM PersonMsgResponse AS pmr
WHERE p.Id = pmr.personID AND p.Received = 'Y' AND
p.MessageID = 1)
AND EXISTS (SELECT 1
FROM PersonMsgResponse AS pmr
WHERE p.Id = pmr.personID AND p.MessageID = 1)
上述查询将返回在任何可用方法中未收到特定消息的人员列表。
答案 2 :(得分:0)
更新:
您可以使用NOT EXISTS()子查询:
select MsgID, PerID from PersonMsgResponse p1
inner join PersonMsgResponse p3 on p1.MsgID=p3.MsgId and p1.PerID=32.PerID and p3.Received='N'
where not exists(select 1 from PersonMsgResponse p2 where p1.MsgID=p2.MsgId and p1.PerID=p2.PerID and p2.Received='Y')
如果你想要人员表中的名字,那么只需要在p1上加入人员表。
答案 3 :(得分:0)
select PersonTable.Person
From Person as PersonTable inner join PersonMsgResponse as ResponseTable
on PersonTable.Id = ResponseTable.PerId
where ResponseTable.Received = 'n'
将select语句添加为
Select Distinct (PersonTable.Person)
如果你不想要重复的人
<强>更新强>
根据您的评论,更改价值,这样任何人都无法拥有&#39; y&#39;收到
select Distinct (PersonTable.Id) , PersonTable.Name, ResponseTable.Received
From Person as PersonTable inner join PersonMsgResponse as ResponseTable
on PersonTable.Id = ResponseTable.PerId
where ResponseTable.Received != 'Y'