选择对帖子及其更新的所有回复

时间:2017-03-12 16:40:18

标签: mysql sql select

我有一个表(MySQL),每个类别都有一些帖子,并且#34;接收"一堆评论。如果您选择了错误的类别,我作为管理员可以更改它,因此我创建了一个表作为一种"更新日志"。

现在我想选择一篇帖子的评论及其更新(例如"您的帖子已更改为Category Something_1")。

表格是:

POSTS: id | title | message | status | id_user | id_category | date

POSTS_COMMENTS: id | id_post | comment_text | date

POSTS_CHANGE_LOG: id | id_post | changed_to | date

你能帮助我吗?

1 个答案:

答案 0 :(得分:0)

假设帖子只能更改一次(即你对POST_CHANGE表有一些限制),你可以使用以下查询:

SELECT p.id, p.id_category as "Original category", IFNULL(pcl.changed_to, p.id_category) as "New Category", pc.id as comment_id, pc.comment_text, pc.date
FROM posts p LEFT JOIN posts_change_log pcl ON p.id = pcl.id_post
JOIN posts_comments pc ON p.id = pc.id_post
WHERE p.id = ?

如果帖子可以多次更改,那么最好在单独的查询中返回/显示帖子历史记录和评论,例如:

SELECT p.id, p.id_category as "Original category", pc.changed_to as "New Category"
FROM post p JOIN posts_change_log pcl
ON p.id = pcl.id_post
WHERE p.id = ?


SELECT *
FROM posts_comments 
WHERE id_post = ?

<强>更新

要合并两个输出,您可以使用UNION ALL运算符,例如:

SELECT comment_text, date, "comment" as "type
FROM posts_comments
WHERE id_post = ?

UNION

SELECT changed_to, date, "change" as "type"
FROM post_change_log
WHERE id_post = ?

ORDER BY date;