三表分離(動態表、評論表、回復表),導致:
CREATE TABLE dynamic_content (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
user_id BIGINT NOT NULL, -- 發布者
content_type TINYINT NOT NULL, -- 1:動態 2:評論 3:回復
parent_id BIGINT DEFAULT 0, -- 父內容 ID,0 表示頂層動態
root_id BIGINT DEFAULT 0, -- 根動態 ID,便於查詢整條鏈
content TEXT NOT NULL,
create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
like_count INT DEFAULT 0,
reply_count INT DEFAULT 0, -- 直接子回復數,冗余字段加速統計
INDEX idx_user_time (user_id, create_time),
INDEX idx_parent (parent_id),
INDEX idx_root (root_id)
);
SELECT * FROM dynamic_content WHERE root_id=0 AND id=? UNION SELECT * WHERE parent_id=? ORDER BY create_timeWITH RECURSIVE (MySQL 8.0+)WHERE user_id=? AND content_type=1| 維度 | 三表分離 | 單表自關聯 |
|---|---|---|
| 擴展性 | 固定 2 層 | 無限層嵌套 |
| 查詢復雜度 | 多 JOIN | 單表索引查詢 |
| 統計維護 | 觸發器/多表更新 | 單表計數器更新 |
| 數據一致性 | 外鍵約束分散 | 自關聯外鍵統一 |