Files
juwan-backend/desc/sql/community/posts.sql
T
2026-02-27 19:17:01 +08:00

58 lines
2.3 KiB
SQL

CREATE TABLE posts (
id BIGINT PRIMARY KEY,
author_id BIGINT NOT NULL,
author_role VARCHAR(20) NOT NULL,
title VARCHAR(500) NOT NULL,
content TEXT NOT NULL,
images TEXT[] DEFAULT ARRAY[]::TEXT[],
tags TEXT[] DEFAULT ARRAY[]::TEXT[],
linked_order_id BIGINT,
quoted_post_id BIGINT REFERENCES posts(id),
like_count INT DEFAULT 0,
comment_count INT DEFAULT 0,
pinned BOOLEAN DEFAULT FALSE,
search_text TEXT GENERATED ALWAYS AS (
title || ' ' || content
) STORED,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
deleted_at TIMESTAMPTZ
);
-- 基础索引
CREATE INDEX idx_posts_author ON posts(author_id, created_at DESC) WHERE deleted_at IS NULL;
CREATE INDEX idx_posts_created ON posts(created_at DESC) WHERE deleted_at IS NULL;
-- 三元组索引用于帖子内容搜索
CREATE INDEX idx_posts_search_trgm ON posts USING gin(search_text gin_trgm_ops)
WHERE deleted_at IS NULL;
-- 全文搜索索引
CREATE INDEX idx_posts_fulltext ON posts USING gin(
to_tsvector('simple', title || ' ' || content)
) WHERE deleted_at IS NULL;
-- 标签 GIN 索引
CREATE INDEX idx_posts_tags_gin ON posts USING gin(tags) WHERE deleted_at IS NULL;
-- 复合索引优化热门排序
CREATE INDEX idx_posts_hot_score ON posts(
(like_count * 2 + comment_count) DESC,
created_at DESC
) WHERE deleted_at IS NULL;
-- 置顶+时间索引
CREATE INDEX idx_posts_pinned_created ON posts(author_id, pinned DESC, created_at DESC)
WHERE deleted_at IS NULL;
-- 关联订单索引
CREATE INDEX idx_posts_linked_order ON posts(linked_order_id)
WHERE linked_order_id IS NOT NULL AND deleted_at IS NULL;
-- 图片数组索引
CREATE INDEX idx_posts_images ON posts USING gin(images) WHERE deleted_at IS NULL;
CREATE TRIGGER trigger_posts_updated_at
BEFORE UPDATE ON posts
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();