奇怪的行爲,我做了一個簡單的表,用於存儲信息:MySQL的:使用UNION,MAX和GROUP BY
+----+--------+----------+--------------+------+
| id | sender | receiver | dt | text |
+----+--------+----------+--------------+------+
| 1 | a | b | ..19.26.00.. | msg1 |
+----+--------+----------+--------------+------+
| 2 | c | b | ..19.26.02.. | msg2 |
+----+--------+----------+--------------+------+
| 3 | b | a | ..19.26.03.. | msg3 |
+----+--------+----------+--------------+------+
我想選擇在交談最近的消息。例如,對於B我想:
+--------------+--------------+------+
| conversation | MAX(maxdt) | text |
+--------------+--------------+------+
| ab | ..19.26.03.. | msg3 |
+--------------+--------------+------+
| cb | ..19.26.02.. | msg2 |
+--------------+--------------+------+
所以我用這個查詢:
SELECT conversation, MAX(maxdt), text FROM
(SELECT CONCAT(sender, receiver) AS conversation, MAX(dt) AS maxdt, text
FROM message
WHERE receiver='b' GROUP BY conversation
UNION
SELECT CONCAT(receiver, sender) AS conversation, MAX(dt) AS maxdt, text
FROM message
WHERE sender='b' GROUP BY conversation) AS x
GROUP BY conversation
但結果是:
+--------------+--------------+------+
| conversation | MAX(maxdt) | text |
+--------------+--------------+------+
| ab | ..19.26.03.. | msg1 |
+--------------+--------------+------+
| cb | ..19.26.02.. | msg2 |
+--------------+--------------+------+
因此,日期時間值是正確的,但文字來自錯誤的元組!
有什麼建議嗎? SQL Fiddle
即其中文本字段在表中列出的順序; GROUP_CONCAT(text),你應該看到 – Cez
你會想回到那張表來獲得適當的'text'值。 –