sql - 无法表达对我的数据库的特定查询

标签 sql postgresql

我有一个用于聊天应用程序的数据库: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/

相关文章:

mysql - 将相似的 URL 分组

SQL (Oracle) Select 没有包含静态数据的实际表

sql - Hive中的时间戳操作

python - SQLAlchemy 与 PostgreSQL 和全文搜索

sql - 根据另外两个表的计数创建一个指标表

sql - PostgreSQL- "ERROR: operator does not exist: interval <= date"

django - 通过 psycopg2 连接执行的查询数

mysql - 最新Group By MYSQL+链接表

c# - 如何修复 "Incorrect syntax near ' )'"。当查询中没有 ) 时

sql - 如何检查与特定时间 SQL 重叠的日期时间