![](/img/trans.png)
[英]How to retrieve a chat msg with sender and receiver username in mysql
[英]Group by sender receiver or receiver sender in MySQL
我正在嘗試制作郵件的收件箱部分。 我的問題是這樣的。
1 a b
2 b a
現在我必須只選擇一個和b之間的對話消息,我也嘗試了一些像這樣的mysql查詢
$query="select *
from messages
where userfrom='a' || userto='a'
group by userto
order by id desc"
但它顯示了兩個會話消息,但我只想顯示一個會話消息
您可以通過查詢嘗試以下條件組:
select *
from messeages
where userfrom='a' OR userto='a'
group by IF(userfrom > userto, userfrom,userto),
IF(userfrom > userto, userto,userfrom)
order by id desc
注意:實際上在GROUP BY
子句中,group by是基於以下邏輯完成的:
GROUP BY greater value of (userfrom,userto), lower value of(userfrom,userto)
例:
userfrom ='a' and userto='b'
userfrom ='b' and userto='a'
在上面兩行中,較大的值是'b',較低的值是'a。因此,從兩行GROUP BY
將首先應用於b
然后應用於a
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.