【问题标题】:Find row where its id is in a list and count is the same查找其 id 在列表中且计数相同的行
【发布时间】:2016-03-31 09:54:01
【问题描述】:

我正在尝试从 UserConversation 表行中查找一个对话,其中 UserConversation.userId 在列表中,并且还找到与 UserConversation.userId 匹配的行具有一定的数量。

所以我有一个对话表。我有一个带有 (userId, conversationId) 字段的 UserConversation 表。我的问题是如何获取 UserConversation.conversationId ,其中 userId 在列表中并且匹配的 list.size 相同:

到目前为止,我有以下查询作为示例:

select uc.conversationid from userconversation uc where uc.userid in(3, 14, 23, 13978, 18488) group by uc.conversationid having count(*)=5 

但此查询为我提供了其他 UserConversation.conversationId,其中对话中可能存在其他 userId。我也只想用计数来限定它。

下面是一个示例:

我的对话表如下所示:

select * from conversation where id=18

id | name            | ownerid
------------------------------
18 | personal group 3|

select * from userconversation where conversationid=18

conversationId | userId
-----------------------
18             | 3
18             | 14
18             | 23
18             | 13978
18             | 18488

现在我想找到用户 ID 为 3,14,23,13978,18488 的对话,并且只有具有该确切用户数量的对话。我应该只获得 18 作为 conversationId 而不是其他可能也有这些以及其他用户的对话。

有人知道如何在 SQL 中做到这一点吗?

谢谢

【问题讨论】:

  • 显示一些示例数据和预期结果。
  • @vkp 我添加了一个示例。
  • 你想得到什么输出?
  • @JCBorlagdan 我想从 select sql 查询的结果中获取值“18”,该查询基于“select * from userconversation where conversationid=18”查询显示有 5 个 userId 与我的匹配第一个 sql 查询。

标签: sql database


【解决方案1】:

我不确定这是否是您要找的,因为您的问题不清楚,但如果这是您想要的,请试试这个。

SELECT userId FROM userconversation uc
INNER JOIN conversation c
ON uc.conversationId = c.Id

【讨论】:

  • 这不是我要查找的查询。让我重申我的问题。如何根据我的第二个示例 sql 查询获得只有我在第一个 sql 查询中指定的用户的唯一 conversationId?
  • hmm,尝试从 userconversation uc 中选择 DISTINCT(uc.conversationid) 其中 uc.userid in(3, 14, 23, 13978, 18488) 由 uc.conversationid 分组,如果 count(*)=5您的第一个查询是正确的,DISTINCT 一词将解决您的问题,
猜你喜欢
  • 1970-01-01
  • 2019-11-29
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 2016-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多