需要帮助复杂的MySQL多查询语句

时间:2016-09-08 10:08:09

标签: mysql sql

我不太习惯使用MySQL而且我在解决正确的查询时遇到问题以获得正确的结果。

我有这些表

CONVERSATIONS
- id, name

MESSAGES
- id, message, conversation_id, user_id

PARTICIPANTS
- id, conversation_id, user_id

USERS
- id, username

我想获得用户参与的所有对话。 然后结果将包括CONVERSATIONS_OBJECT作为父对象,最后/最新MESSAGES_OBJECT(仅1)和所有PARTICIPANTS。

示例结果:

[ // PARENT ARRAY
    { // CONVERSATION OBJECT
        last_message: {}, // THE VERY LAST MESSAGE FOR THIS CONVERSATION
        participants:  // ALL PARTICIPANTS FOR THIS CONVERSATION
        [
            {user1}, {user2} // USERS OBJECT ARRAY
        ]
    },
    { // CONVERSATION OBJECT
        last_message: {}, // THE VERY LAST MESSAGE FOR THIS CONVERSATION
        participants:  // ALL PARTICIPANTS FOR THIS CONVERSATION
        [
            {user1}, {user2} // USERS OBJECT ARRAY
        ]
    },
    { // CONVERSATION OBJECT
        last_message: {}, // THE VERY LAST MESSAGE FOR THIS CONVERSATION
        participants:  // ALL PARTICIPANTS FOR THIS CONVERSATION
        [
            {user1}, {user2} // USERS OBJECT ARRAY
        ]
    }

1 个答案:

答案 0 :(得分:0)

你可以这样做:

SELECT
  u.username,
  c.name AS ConversationName,
  pu.username AS ParticipantName 
FROM users as u 
LEFT JOIN
(
  SELECT user_id, MAX(conversation_id) AS Latestconversation_id
  FROM participants 
  GROUP BY user_id
) AS p ON u.id = p.user_id
LEFT JOIN CONVERSATIONS AS c ON c.id = p.Latestconversation_id
LEFT JOIN users as up ON up.id = p.user_id;