簡體   English   中英

查找具有相同值的行 (PostgreSQL)

[英]Finding rows with identical values (PostgreSQL)

我目前正在使用 PostgreSQL 進行聊天功能,我存儲對話的方式是將每個對話的成員存儲在一個名為 conversationMember 的單獨表中。

| convomemberId | conversationId                       | userId                               |
-----------------------------------------------------------------------------------------------
| UUID          | ddbde2ae-17f3-47da-94d2-a3dffd9ee7e2 | d2119e47-b122-41b5-a425-afde47fd36ba |
-----------------------------------------------------------------------------------------------
| UUID          | ddbde2ae-17f3-47da-94d2-a3dffd9ee7e2 | f9a3572c-3424-408f-8c06-6422728ef847 |

如您所見,我將每一行都存儲有 conversationId 和 userId,以便我可以輕松檢查哪個用戶在對話中。 但目前我現在需要一個 function 來檢查數據庫中是否存在兩個用戶之間的對話。 所以我想知道是否有辦法讓我執行 SQL 查詢以獲取基於 2 個用戶 ID 的會話 ID。

例如
輸入:用戶 ID:“d2119e47-b122-41b5-a425-afde47fd36ba”和用戶 ID:“f9a3572c-3424-408f-8c06-6422728ef847”
Output:conversationId:“ddbde2ae-17f3-47da-94d2-a3dffd9ee7e2”

你可以這樣做(結果在這里

select c1.conversation_id
from conversation c1, conversation c2
where c1.conversation_id = c2.conversation_id
and c1.user_id = 'd2119e47-b122-41b5-a425-afde47fd36ba'
and c2.user_id = 'f9a3572c-3424-408f-8c06-6422728ef847';

試試這個 select:

select cm.userId, dup.conversationId from 
       (select count(*) cnt, conversationId from conversationMember group by conversationId having count(*)>1) dup, 
        conversationMember cm 
        where cm.conversationId=dup.conversationId;

結果應該是:

cm.userId                               dup.conversationId 
d2119e47-b122-41b5-a425-afde47fd36ba    ddbde2ae-17f3-47da-94d2-a3dffd9ee7e2 
f9a3572c-3424-408f-8c06-6422728ef847    ddbde2ae-17f3-47da-94d2-a3dffd9ee7e2
select t1.conversationId 
       from conversationMember t1 inner join conversationMember t2 on 
       (t1.conversationId=t2.conversationId) 
   where t1.userId='d2119e47-b122-41b5-a425-afde47fd36ba' 
     and t2.userid='f9a3572c-3424-408f-8c06-6422728ef847';

結果

            conversationid
--------------------------------------
 ddbde2ae-17f3-47da-94d2-a3dffd9ee7e2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM