<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="top.lejings.demo.mapper.PostsMapper">
    <!--  同包同名，工作空间一致，id一致，返回值一致即resultType：单条结果的封装类的全类名  -->
    <select id="postsOverview" resultType="top.lejings.demo.pojo.Posts">
        SELECT
        p.post_id,
        p.user_id,
        COUNT(CASE WHEN r.type = 'like' THEN 1 END) AS Likes,
        u.username,
        p.title,
        p.updated_at
        FROM
        posts p
        JOIN
        users u ON p.user_id = u.user_id
        LEFT JOIN
        reactions r ON p.post_id = r.post_id AND r.type = 'like'
        GROUP BY
        p.post_id, p.user_id, u.username, p.title, p.content, p.updated_at, p.priority
        ORDER BY
        ${by} DESC;
    </select>
    <select id="postsEssay" resultType="top.lejings.demo.pojo.Posts">
        SELECT
        p.post_id,
        p.user_id,
        u.username,
        p.title,
        p.content,
        p.updated_at,
        COALESCE(r.like_count, 0) AS like_count, -- 使用 COALESCE 处理 NULL 值
        GROUP_CONCAT(DISTINCT r.user_id) AS like_user_ids -- 确保 user_id 不重复
        FROM
        posts p
        JOIN
        users u ON p.user_id = u.user_id -- 加入 users 表以获取用户名
        LEFT JOIN
        (SELECT
        post_id,
        COUNT(*) AS like_count,
        GROUP_CONCAT(user_id) AS user_id
        FROM
        reactions
        WHERE
        type = 'like'
        GROUP BY
        post_id) r ON p.post_id = r.post_id
        WHERE
        p.post_id = #{post_id}
        AND u.status IN ('normal', 'admin') -- 修改这里的条件以直接使用 u.status
        GROUP BY
        p.post_id, p.user_id, u.username, p.title, p.content, p.updated_at, r.like_count;

    </select>
    <insert id="postsNew">
        INSERT INTO posts (user_id, title, content,  priority)
        VALUES (#{user_id}, #{title}, #{content}, 0);
    </insert>
</mapper>