【问题标题】:How can I run this SELECT query?如何运行此 SELECT 查询?
【发布时间】:2020-02-22 22:59:11
【问题描述】:

我正在为应用程序开发消息功能,并且我在 MSSQL 中有以下表,以及一个用户表(未列出):

CREATE TABLE Thread (
    id int IDENTITY(1,1),
    createdAt datetimeoffset NOT NULL,
    CONSTRAINT PK_Thread_id PRIMARY KEY (id)
) GO

CREATE TABLE ThreadParticipant (
    userId int NOT NULL,
    threadId int NOT NULL,
    createdAt datetimeoffset NOT NULL,
    CONSTRAINT PK_userId_threadId PRIMARY KEY (userId, threadId),
    CONSTRAINT FK_ThreadParticipant_userId FOREIGN KEY (userId) REFERENCES User(id) ON DELETE CASCADE,
    CONSTRAINT FK_ThreadParticipant_threadId FOREIGN KEY (threadId) REFERENCES Thread(id) ON DELETE CASCADE
) GO

我想查询ThreadParticipant 表是否存在只包含给定用户ID 集的线程,假设用户1,3,5,7。每个Thread 都包含一组唯一的用户ID。我如何查询这些数据?如果它更简单,我可以将一些逻辑放在服务器(node.js)中。我在网上查找了重复的问题,但找不到任何问题,但我不确定如何准确地表达问题以找到它们(如果它们在附近)。

【问题讨论】:

    标签: sql tsql select


    【解决方案1】:

    您可以将聚合与 having 子句一起使用:

    select tp.threadid
    from ThreadParticipant tp
    where tp.userid in (1, 3, 5, 7)
    group by tp.threadid
    having count(*) = 4;
    

    编辑:

    如果您希望这些用户,请使用:

    select tp.threadid
    from ThreadParticipant tp
    group by tp.threadid
    having sum(case when tp.userid in (1, 3, 5, 7) then 1 else 0 end) = 4
    

    【讨论】:

    • 这似乎比其他答案更简单,但这也选择了包含其他 id 的情况,例如(1,3,5,7,9), (1,3,5,7,9,11) 等。但是您的回答确实帮助我找到了重复的here。有了那里的信息,我设置了以下内容: SELECT tp.threadId FROM dbo.ThreadParticipant tp WHERE tp.userId IN (2, 25, 48) GROUP BY tp.threadId HAVING COUNT()=( SELECT COUNT () FROM ThreadParticipant tp2 WHERE tp.threadId = tp2.threadId GROUP BY tp2.threadId ) AND Count(*)=3;
    • @cweber105 。 .我就是这样解释你的问题的。我根据您的评论编辑了答案。
    【解决方案2】:

    你可以使用exists:

    select 
        t.*,
        case 
            when exists (
                select 1 
                from threadParticipant p 
                where p.threadId = t.id and p.userid not in (1, 3, 5, 7)
            ) 
            then 'not only these users'
            else 'these users only'
        end status
    from thread t
    

    status 列指示线程是否包含除1, 3, 5, 7 以外的用户。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-30
      • 2011-05-24
      • 2010-12-14
      • 2016-11-01
      • 1970-01-01
      • 2015-07-21
      • 2014-12-31
      • 2011-09-25
      相关资源
      最近更新 更多