如何检查两个用户是否进行私人聊天?的SQL

问题描述

enter image description here

如何编写sql或linq查询以检查两个用户是否具有公共私人聊天(isGroup == false)

解决方法

如果我正确地遵循了您的规定,则可以使用两个chats子查询来过滤exists表,对于想要为其进行普通聊天的每个用户一次:

select c.*
from chats c
where 
    isGroup = 0
    and exists (select 1 from participants p where p.chatID = c.id and p.participantId = ?)
    and exists (select 1 from participants p where p.chatID = c.id and p.participantId = ?)

这为您两个用户共同的私人聊天提供了一行。

,

有很多方法可以实现这一目标。取决于您的行数和现有索引,方法的执行方式可能会完全不同

  1. 您可以在INNER JOINChats表之间执行两个Participants,并在每个表中检查所需的participantid(每个{ {1}}代表参数化查询中的ID之一。这将返回所有(至少)涉及两个所需用户的非群组聊天

    ?
  2. 另一种可能性(可能是效率较低)可能是查询SELECT c.* FROM chats c INNER JOIN participants p1 ON p1.chatid = c.id AND p1.participantid = ? INNER JOIN participants p2 ON p2.chatid = c.id AND p2.participantid = ? WHERE c.isgroup = 0 以进行涉及至少所需用户的所有聊天,然后将此结果与Participants表结合并过滤为私有聊天。

    Chats
  3. 您可以用作@GMB suggested并使用 WITH userchats(chatid) AS ( SELECT chatid FROM participants WHERE participantid IN (?,?) GROUP BY chatid HAVING COUNT(*) = 2) SELECT c.* FROM chats c INNER JOIN userchats uc ON c.chatid = uc.chatid WHERE c.isgroup = 0 子查询。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...