[英]How to select unique combination of 2 columns in MYSQL
例如,如果我有此消息表,並且它具有此3列
╔══════════╦══════════╦══════════╦══════════╦
║ from_user║ to_user ║ message ║ date ║
╠══════════╬══════════╣══════════║══════════║
║ 1 ║ 2 ║ text ║timestamp ║
║ 1 ║ 3 ║ text ║ .. ║
║ 2 ║ 1 ║ text ║ .. ║
║ 2 ║ 3 ║ text ║ .. ║
║ 3 ║ 1 ║ text ║ .. ║
║ 1 ║ 2 ║ text ║ .. ║
║ 1 ║ 4 ║ text ║ .. ║
║ 3 ║ 1 ║ text ║ .. ║
╚══════════╩══════════╩══════════╩══════════╩
如果要選擇用戶1進行的所有對話(我在“來自_user”列中的所有記錄以及在“ to_user”中的位置的所有記錄),那么我想獲得用戶所涉及的所有內容,那么“對話”將是:
因此,按日期順序,我每次對話只會得到1條記錄(最后一條)
╔══════════╦══════════╦══════════╦══════════╦
║ from_user║ to_user ║ message ║ date ║
╠══════════╬══════════╣══════════║══════════║
║ 1 ║ 2 ║ text ║timestamp ║
║ 1 ║ 3 ║ text ║ .. ║
║ 2 ║ 1 ║ text ║ .. ║
║ 2 ║ 3 ║ text ║ .. ║
║ 3 ║ 1 ║ text ║ .. ║
║ 1 ║ 2 ║ text ║ .. ║<--- i would get this one third (conv between 1&2)
║ 2 ║ 3 ║ text ║ .. ║
║ 1 ║ 4 ║ text ║ .. ║<--- i would get this one second (conv between 1&4)
║ 3 ║ 1 ║ text ║ .. ║<--- i would get this one first (conv between 1&3)
╚══════════╩══════════╩══════════╩══════════╩
我不確定如何解決此問題,我應該使用GROUP BY嗎?
編輯:對話是指用戶發送或接收消息時,對話可以有多個消息,也可以只有一個。 我標記為要獲得的結果是每個對話的最后記錄,誰發送和接收誰都無所謂,我希望用戶進行的每個對話的最后記錄。
這種嘗試是我所能達到的最接近的目標
SELECT id, from_user, to_user
FROM messages
WHERE (to_user = '$usr_id' OR from_user = '$usr_id') AND id IN
(
SELECT MAX(id)
FROM messages
GROUP BY from_user, to_user
)
但是我正在獲取每個組合的最后一條記錄,例如,如果有
id from_user to_user
1 1 2
2 1 3
3 4 1
4 2 1
5 1 2
輸出為:
id from_user to_user
1 1 2
2 1 3
3 4 1
4 2 1
如您所見,沒有選擇ID為5的記錄,因為它被重復了,但是ID為1和4的記錄是相同的對話,因此只應輸出其中之一
出於可讀性考慮,我將向您展示第一個查詢,該查詢提供所需的結果,除非被查詢的用戶位於to_user列上:
SELECT from_user, to_user, max(msg_date) latest, id
FROM messages
WHERE to_user = 1
OR from_user = 1
GROUP BY from_user, to_user
ORDER BY latest desc;
要使用group by解決此問題,您需要在用戶位於to_user端時切換from_user和to_user列的值。 您可能還需要標記“ switched”來指示這些情況。 因此,您需要的是:
SELECT id, main_user, other_user, switched, max(msg_date) latest, msg_date, msg
FROM (SELECT id, 1 main_user, if (from_user = 1, to_user, from_user) other_user,
if (from_user=1, 0, 1) switched, msg_date, msg
FROM messages
WHERE to_user = 1
OR from_user = 1) user_messages
GROUP BY main_user, other_user
ORDER BY msg_date desc;
在同一查詢中,可以像子查詢中那樣使用IF使用“ switched”回退from_user,to_user。 我現在沒有放它以便於閱讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.