<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ruoyi.system.mapper.CommunityChatMsgMapper">
	<select id="getChatListWithLatestMessage" resultType="com.ruoyi.system.domain.vo.SysUserVo">
        SELECT u.user_id                                                             AS id,
               u.nick_name                                                           as nickName,
               u.user_name                                                           as username,
               u.avatar                                                              as avatar,
               (SELECT u2.nick_name from sys_user u2 where u2.user_id = r.sender_id) as senderNickName,
               r.is_read                                                             as isRead,
               r.content                                                             AS msg,
               r.create_time                                                         AS msgTime
        FROM (SELECT CASE
                         WHEN sender_id = #{userId} THEN receiver_id
                         ELSE sender_id
                         END          AS chat_user_id,
                     MAX(create_time) AS latest_time
              FROM community_chat_msg
              WHERE (sender_id = #{userId}
                  OR receiver_id = #{userId})
                and type = #{type}
              GROUP BY chat_user_id) latest
                 JOIN community_chat_msg r ON
            (
                (r.sender_id = #{userId} AND r.receiver_id = latest.chat_user_id
                    OR
                 r.sender_id = latest.chat_user_id AND r.receiver_id = #{userId})
                    AND r.create_time = latest.latest_time and r.type = #{type}
            )
                 JOIN sys_user u ON
            u.user_id = latest.chat_user_id
        ORDER BY latest.latest_time DESC
    </select>
</mapper> 