MySQL查询常见问题

一、先排序后分组

1、MySQL版本5.6

首先order by然后group by

SELECT
    id,
    chat_id,
    content,
    create_time 
FROM
    ( SELECT id, chat_id, content, create_time FROM im_chat_message ORDER BY create_time DESC ) a 
GROUP BY
    chat_id 
ORDER BY
    create_time DESC

2、MySQL版本5.7

MySQL5.7对子查询进行了优化,认为子查询中的order by可以进行忽略,只要Derived table里不包含如下条件就可以进行优化:UNION clause、GROUP BY、DISTINCT、Aggregation、LIMIT or OFFSET

SELECT
    id,
    chat_id,
    content,
    create_time 
FROM
    ( SELECT id, chat_id, content, create_time FROM im_chat_message ORDER BY create_time DESC LIMIT 999999999 ) a 
GROUP BY
    chat_id 
ORDER BY
    create_time DESC

3、MySQL版本>=8.0

采用 ROW_NUMBER() over ( PARTITION BY chat_id

你可能感兴趣的:(数据库,sql,数据库)