簡體   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