![](/img/trans.png)
[英]MySQL - Need to get only the latest data based on the date/time column in the child table for each record in the parent table
[英]MYSQL Join - Parent and Child table join and get only the latest record from the child table
我有兩張桌子帖子和評論
發布表
Post_id
Post_content
評論表
comment_id
Comment
post_id
created_date
一個帖子可以有多個評論或零評論
我的要求是使用左外部聯接獲取有關帖子的最新評論。
我的意思是,結果應為包含以下各列的帖子的一條記錄。
post_id,post_content ,comment_id,comment
用簡單的話來說,帖子應該和他們的最新評論相處(如果存在)。
(目前,系統先獲取帖子,然后再轉到服務器以顯示最新評論,因為我們一開始只顯示一個評論,所以考慮將它們合而為一。...不確定最好的方法是什么如果要顯示多個評論..?)
謝謝
問候
基蘭
SELECT Post.post_id, post_content, comment_id, comment
FROM
Post LEFT JOIN Comments
ON Post.post_id = Comments.post_id
AND created_date = (
SELECT MAX(created_date)
FROM Comments
WHERE Post.post_id = Comments.post_id
)
順便說一句,你應該考慮索引Comments {post_id, created_date}
以獲得最佳性能,但要留意如果你正使用InnoDB非主鍵索引開銷(請參見“集群的缺點”,在這篇文章中 )。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.