我有一个用于聊天应用程序的数据库:http://sqlfiddle.com/#!17/9e068/1
让我们获取至少从用户“John”收到一条消息的所有用户。我想定义已向所有已从用户“John”收到至少一条消息的用户发送消息(一条或多条)的所有其他用户的数量
我认为解决这个问题的关键是双重否定。表达式:“已向用户 John 消息的所有收件人发送消息的用户 U”等于表达式“用户“John”没有用户 U 未向其发送消息的收件人”
我已经写了一段关于我的方法的代码,但它不正确:
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')
最佳答案
什么双重否定?这看起来很复杂。
一种方法是比较计数——但它们必须是正确的计数:
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);
关于sql - 无法表达对我的数据库的特定查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56047513/