如何按字段分组然后按不同的字段排序然后限制

时间:2011-12-15 02:15:13

标签: mysql sql

我有一个类似的查询:

SELECT _threads.*, _messages.*
FROM _threads
LEFT JOIN _messages
ON _threads.thread_id = _messages.message_thread_id
WHERE _threads.thread_servicer_id = 'jG5s2b6TRs'
GROUP BY _threads.thread_customer_id

返回的内容如下: enter image description here

如何修改查询,以便按thread_customer_idmessage_time排序,只选择最新message_time的行。

2 个答案:

答案 0 :(得分:1)

根据您评论中的额外信息,我认为这将提供您想要的结果

SELECT t.*, m.*, MAX(m.message_time)
FROM _threads t
INNER JOIN _messages m
ON t.thread_id = m.message_thread_id
WHERE t.thread_servicer_id = 'jG5s2b6TRs'
GROUP BY t.thread_customer_id
ORDER BY m.message_time

答案 1 :(得分:1)

预先查询按客户分组的主题/消息,并获取每个服务ID过滤器的最长过帐时间。从那以后,它将返回单个客户/日期时间。然后,将其重新加入消息表AGAIN,但仅限于匹配的日期/时间,然后再添加到与您的服务商ID匹配的线程中。以防万一相同的日期/时间发布多个消息不同的服务器

SELECT 
      T2.*, 
      M2.*
   FROM
      ( select T.thread_Customer_id,
               MAX( M.Message_Time ) as LatestPost
           from
              _Threads T
                 JOIN _Messages M
                    ON T.Thread_ID = M.Message_Thread_ID
           where
              T.thread_servicer_id = 'jG5s2b6TRs'
           GROUP BY 
              T.thread_customer_id ) PreMax

      JOIN _Messages M2
         on PreMax.LatestPost = M2.Message_Time

         JOIN _Threads T2
            on M2.Message_Thread_ID = T2.Thread_ID
           AND T2.Thread_Customer_ID = PreMax.Thread_Customer_ID
           AND T2.Thread_Servicer_ID = 'jG5s2b6TRs'

   ORDER BY 
      M2.Message_Time DESC