MySQL是一种关系型数据库管理系统,广泛应用于各种Web应用程序中。评论回复功能通常用于在线论坛、博客、电商网站等,允许用户对已有评论进行回复,形成多层次的交流。
解决方案:
可以设计两个表:comments
和 replies
。
CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY,
post_id INT NOT NULL,
user_id INT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE replies (
id INT AUTO_INCREMENT PRIMARY KEY,
comment_id INT NOT NULL,
user_id INT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (comment_id) REFERENCES comments(id)
);
解决方案:
SELECT * FROM replies WHERE comment_id = ?;
解决方案:
WITH RECURSIVE reply_tree AS (
SELECT id, comment_id, user_id, content, created_at
FROM replies
WHERE comment_id = ?
UNION ALL
SELECT r.id, r.comment_id, r.user_id, r.content, r.created_at
FROM replies r
INNER JOIN reply_tree rt ON r.comment_id = rt.id
)
SELECT * FROM reply_tree;
comment_id
和id
字段上建立索引,以提高查询性能。CREATE INDEX idx_comment_id ON replies(comment_id);
CREATE INDEX idx_id ON replies(id);
希望这些信息对你有所帮助!如果有更多具体问题,欢迎继续提问。
领取专属 10元无门槛券
手把手带您无忧上云