<?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.yunzhi.marketing.mapper.TaChatMapper">
    <select id="getChatHistory" resultType="com.yunzhi.marketing.entity.TaChat">
        SELECT
            *
        FROM
            ta_chat t
        WHERE
            (
                t.send_person = #{from}
                AND t.receive_person = #{to}
            )
        OR (
            t.send_person = #{to}
            AND t.receive_person = #{from}
        )
        ORDER BY
            t.create_date DESC
    </select>

    <select id="getChatWith" resultType="com.yunzhi.marketing.entity.TaChat">
        SELECT
            a.*
        FROM
            ta_chat a
        JOIN (
            SELECT DISTINCT
                (
                    IF (
                        t.send_person &gt; t.receive_person,
                        CONCAT(
                            t.send_person,
                            t.receive_person
                        ),
                        CONCAT(
                            t.receive_person,
                            t.send_person
                        )
                    )
                ),
                max(t.chat_id) AS chat_id
            FROM
                ta_chat t
            WHERE
                t.send_person = #{person}
            OR t.receive_person = #{person}
            GROUP BY
            IF (
                t.send_person &gt; t.receive_person,
                CONCAT(
                    t.send_person,
                    t.receive_person
                ),
                CONCAT(
                    t.receive_person,
                    t.send_person
                )
            )
        ) b ON a.chat_id = b.chat_id
        ORDER BY a.chat_id desc
    </select>

    <select id="getUnReadMessage" resultType="Integer">
        SELECT
            count(1) AS total
        FROM
            ta_chat t
        WHERE
        (
            t.send_person = #{to}
            AND t.receive_person = #{from}
        )
        AND IFNULL(t.is_read, 0) = 0
    </select>

    <select id="getAllUnReadMessage" resultType="Integer">
        SELECT
            count(1) AS total
        FROM
            ta_chat t
        WHERE
           t.receive_person = #{personId}
        AND IFNULL(t.is_read, 0) = 0
    </select>
</mapper>
