簡體   English   中英

Mysql-使用A列和B列選擇和分組行,其中A.value和B.value = x和y或y和x

[英]Mysql - Select & Group rows with A column, and B column where A.value and B.value = x and y or y and x

我有一個表,其中有2個數字( int )值(ID)作為sender_idreceiver_id

我正在嘗試將這些行分組為“對話”。 之間的對話:

sender_id = 1, and receiver_id = 5,

是相同的對話,其中sender_id = 5receiver_id = 1

因此,當我獲取數據庫行時,每次會話只希望有1行。

我將為特定用戶獲取這些對話。 用戶ID(我已經知道並將其稱為userId )可以位於sender_idreceiver_id

所以我的算法是這樣的:

Select All rows 
from Database, 
where sender_id = userId OR receiver_id = userId, 
group by sender_id+user_id

結果行必須包含另一列值(不是等於userId列值),盡管它可以包含兩者,但我必須通過將它們與我擁有的userId進行比較來檢測另一列。

老實說,我一直對SQL手冊不滿意。 由於某種原因,我無法從那里找到我需要的東西。 原諒我..

我不確定是否應該創建臨時表或使用SQL SUM函數,或者是否可以使用GROUP BY sender_id+receiver_id

更多信息(不確定是否相關):我正在使用php該表還有更多列,如record_id, create_date and read_date

非常感謝您的幫助和答復。

更新:我的問題的解決方案在下面標記。 但是,我遇到了另一個我想分享的問題,因為它可能會幫助以后查看此問題的人。

我遇到的問題是,當我顯示對話時,我想顯示最后一條消息行。 現在,完成分組后,分組會在找到的第一行上堆疊。 我要相反。 我希望返回的行包含每個會話的最后一條消息行。

我可以使用以下查詢來做到這一點。 請注意,這只是這樣做的一種方式,我不確定該查詢的性能。 我將稍后對其進行測試,並在需要時進行更新。

$ this-> id是我要顯示其對話的用戶的ID。

"SELECT t1.* FROM table t1 
        INNER JOIN (
            SELECT sender_id, receiver_id, max(create_date) lastCreateDate 
            FROM table 
            WHERE receiver_id = ".$this->id." OR sender_Id = ".$this->id." 
            GROUP BY GREATEST(sender_id ,receiver_id), LEAST(sender_id,receiver_id)
        ) t2
        ON ((t1.sender_id = t2.sender_id 
        OR t1.sender_id = t2.receiver_id) 
        AND t1.create_date = t2.lastCreateDate) 
        ORDER BY create_date DESC LIMIT 0,15"
GROUP BY max(sender_id, receiver_id), min(sender_id, receiver_id)

最小返回最低值,最大返回最大值:

GROUP BY LEAST(sender_id, receiver_id), GREATEST(sender_id, receiver_id)

暫無
暫無

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

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