我有一个聊天应用程序数据库:http://sqlfiddle.com/#!17/9e068/1
让我们接受从用户“ John”收到至少一条消息的所有用户。我想定义已向所有从“约翰”用户那里收到至少一条消息的用户发送了一条消息(一个或多个)的所有其他用户的数量
我认为解决此查询的关键是双重否定。表达式:“已将消息发送给该用户的John消息的所有收件人的用户U”等于表达式“用户U尚未向其发送消息的来自用户“ John”的没有收件人”
我已经编写了有关我的方法的代码,但这是不正确的:
SELECT U.name
FROM Users as U
WHERE NOT EXISTS
(SELECT M.recipient
FROM Messages as M
WHERE M.sender = U.uid)
EXCEPT
(SELECT mm.recipient
FROM Users as uu ,Messages as mm
WHERE uu.uid = mm.sender and uu.name = 'John')
答案 0 :(得分:2)
什么双重否定?这看起来很复杂。
一种方法是比较计数-但它们必须是正确的计数:
select u.uid, count(*), count(distinct m.recipient)
from messages mj join
users uj
on mj.sender = uj.uid join
users u
on u.uid <> uj.uid left join -- all combinations of john's recipients and other users
messages m
on m.recipient = mj.recipient and
m.sender = u.uid
where uj.name = 'John'
group by u.uid
having count(distinct m.recipient) = count(distinct mj.recipient);