我試圖在一行中獲取與它關聯的對話列表和與會者,以及給定用戶的最後一條消息。我正在尋找的結果是這樣的:SQL查詢同一行中同一列的多個值
**| conversationId | participants | text | timestamp |**
67 aester,bester Hello 00:00:00
上述模型只是一行。我正在試圖獲得具有上述結果的所有行。文本列是與該對話關聯的最後一條消息。
這裏是我的模型:
用戶
userId|username|
87 aester
89 cester
96 bester
對話
|conversationId|
67
68
消息
| messageId | text | timestamp | conversation_id | user_id
41 Hello 00:00:00 67 87
42 Hey 00:00:00 68 89
UserConversations
| id | conversation_id | user_id
3 67 87
4 67 96
5 68 89
如何查詢上述模型以獲得期望的結果?
當前的更新:
SELECT conversations.`conversationId` as conversationId,
GROUP_CONCAT(users.`username`) as participants FROM users
LEFT JOIN user_conversations
ON users.`userId` = user_conversations.`user_id`
LEFT JOIN conversations
ON user_conversations.`conversation_id` =
conversations.`conversationId`
WHERE EXISTS (SELECT * FROM user_conversations WHERE
user_conversations.user_id = 87)
GROUP BY conversations.`conversationId`;
以上是生產這是我想要的只是我無法弄清楚如何讓每行也是在最後的消息:
| conversationId | participants |
67 aester,bester
68 cester
檢查[** GROUP_CONCAT()**](https://www.w3resource.com/mysql/aggregate-functions-and-grouping/aggregate-functions-and-grouping-group_concat.php) –
我試圖使用GROUP_CONCAT,但它返回同一行上的所有參與者,即使它們不屬於對話 – samuscarella
向我們顯示數據庫模式,樣本數據,當前和預期輸出。 \t請閱讀[**如何提問**](http://stackoverflow.com/help/how-to-ask) \t \t這裏是一個偉大的地方[** START **] (http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/)來了解如何提高您的問題質量並獲得更好的答案。 \t [**如何創建最小,完整和可驗證示例**](http://stackoverflow.com/help/mcve) –