MYSQL GROUP BY分组按时间降序

牛客网中/高级项目 toutiao_第二次课代码 解决spring-boot兼容velocity

站内信页面展示需求:将conversation_id分组 按created_date降序排列

(不同的人越新的私信排在越前面 同一个人的多条私信也按时间降序)

表(message) 结构:

MYSQL GROUP BY分组按时间降序_第1张图片

id=10分别和id=8、id=9的最新互动私信:
MYSQL GROUP BY分组按时间降序_第2张图片

需要的效果:

MYSQL GROUP BY分组按时间降序_第3张图片

如果按牛客网视频的写法:

sql

select *, count(id) as cnt from (select * from message where from_id=10 or to_id=10 order by created_date desc) tt group by conversation_id order by id desc ;

mybatis:

TABLE_NAME = message ;

@Select({"select *, count(id) as id from ( select * from ", TABLE_NAME,
        " where from_id=#{userId} or to_id=#{userId} order by created_date desc) tt group by conversation_id order by created_date desc limit #{offset}, #{limit}"})

运行结果:

MYSQL GROUP BY分组按时间降序_第4张图片

明显没有满足需求!

下面介绍三种可行的sql语句:

1)为我所用

SELECT *
FROM message col
WHERE col.created_date in (
SELECT max(created_date)
FROM message where from_id=10 or to_id=10
GROUP BY conversation_id) 
order by created_date desc;

2)

SELECT *
FROM message col
WHERE col.created_date = (
SELECT max(created_date)
FROM message
WHERE col.conversation_id = conversation_id)
order by created_date desc;

3)

SELECT *
FROM (SELECT conversation_id, max(created_date) created_date
FROM message
GROUP BY conversation_id
) b JOIN message a ON a.conversation_id = b.conversation_id AND a.created_date = b.created_date;

letter.html:

MYSQL GROUP BY分组按时间降序_第5张图片

letterDetail.html:

MYSQL GROUP BY分组按时间降序_第6张图片
参考: MySQL之——GROUP BY分组取字段最大值.

你可能感兴趣的:(Java,Mysql,牛客网中/高级项目,Spring/Spring,boot,SSM)