繁体   English   中英

SQL:从多行获取单个结果 ID

[英]SQL: Get single result id from multiple rows

我有两个看起来像这样的表:

conversations

conversation_id | type    | updated_at
     50         | private | 2018-01-01 15:50:51
     30         | group   | 2019-01-01 15:50:49
    100         | private | 2018-01-01 15:50:55

conversation_participants

user_id | conversation_id
1       | 100
3       | 50
5       | 99
6       | 50
6       | 30
3       | 30
2       | 30

我怎么能现在选择conversation_id取决于两个user_id和谈话的类型?

例如,给我来自用户 3 和 6 的conversation_id ,这是私有的。 所以我会得到conversation_id 50。

到目前为止我的方法:

SELECT * 
FROM conversation_participants as cp 
    LEFT JOIN conversations as c 
       ON c.conversation_id = cp.conversation_id
 WHERE c.type = 'private' 

但是如何根据不同的行获取conversation_id

首先,您需要知道哪些转换是私密的

SELECT conversation_id 
FROM conversations c
WHERE c.type = 'private' 

然后您需要查看使用 SELF JOIN 的用户 3 和 6 的对话

SELECT conversation_id
FROM conversation_participants cp1
JOIN conversation_participants cp2
  ON cp1.conversation_id = cp2.conversation_id
WHERE cp1 = 3
  AND cp2 = 6 

现在您只过滤私人对话

SELECT conversation_id
FROM conversation_participants cp1
JOIN conversation_participants cp2
  ON cp1.conversation_id = cp2.conversation_id
WHERE conversation_id IN (  SELECT conversation_id 
                            FROM conversations c
                            WHERE c.type = 'private' )
 AND cp1 = 3
 AND cp2 = 6

您还可以使用第三个连接

SELECT conversation_id
FROM conversation_participants cp1
JOIN conversation_participants cp2
  ON cp1.conversation_id = cp2.conversation_id
JOIN conversations c
  ON cp1.conversation_id = c.conversation_id   
WHERE c.type = 'private' 
 AND cp1 = 3
 AND cp2 = 6

我建议您首先根据参与者选择对话。 例如:

SELECT * 
FROM conversation_participants cp
WHERE cp.user_id IN (3, 6)

要仅包含私人对话,您必须将conversation_participants conversations加入conversations

SELECT * 
FROM conversation_participants cp
    INNER JOIN conversations c ON
        c.conversation_id = cp.conversation_id
WHERE
    cp.user_id IN (3, 6)
    AND c.type = 'private'

当然,此查询将为对话中的每个用户包含一行。 如果你只想有 1 行,你可以按对话分组。 像这样的东西:

SELECT
    c.conversation_id,
    c.updated_at,
    COUNT(*) AS participant_count
FROM conversation_participants cp
    INNER JOIN conversations c ON
        c.conversation_id = cp.conversation_id
WHERE
    cp.user_id IN (3, 6)
    AND c.type = 'private'
 GROUP BY 
    c.conversation_id,
    c.updated_at

您需要使用GROUPING子句,并添加一个HAVING子句来优化您的查询(特别是如果您想搜索指定超过 2 个参与者的对话):

SELECT
    c.conversation_id,
    COUNT(*) AS participant_count
FROM conversations c
    INNER JOIN conversation_participants cp ON
        cp.conversation_id = c.conversation_id
WHERE
    c.type = 'private'
    AND cp.user_id IN (3, 6)
 GROUP BY c.conversation_id
 HAVING COUNT(*) = 2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM