I have 3 tables:
-categories (-categories not important)
-articles
-comments
example:
-articles
I have 10000+ articles
-comments
I have 10000+ comments for random -articles
-I'm trying to show "last 5 comments"
OF articles.article_id s= in(1, 2, 3, 4, 5)
WITH order by comments.comment_id desc
WITH categories.category_id,categories.category_name
-SQL-QUERY-1:
select
comments.comment_id,comments.comment_title,comments.article_id,
articles.article_id,articles.article_title,articles.category_id,
categories.category_id,categories.category_name from comments
left join (articles,categories) on (comments.article_id=articles.article_id and articles.category_id=categories.category_id)
where (comments.article_id in(1,2,3,4,5))
ORDER BY `comments`.`comment_id` DESC limit 0 , 5
Please focus to comments_id
and article_id
columns
![result 1](https://i.imgur.com/WiE9Eh6.png)
As you see;
- comments.comment_id desc order +OK
109
108
107
106
105
comments.article_id s +OK
1 - 2 - 3 - 4 - 5
but result list shows **2 comments of every article**
-I need to "group" articles.article_id s
so I add " group by comments.article_id"
-SQL-QUERY-2:
select
comments.comment_id,comments.comment_title,comments.article_id,
articles.article_id,articles.article_title,articles.category_id,
categories.category_id,categories.category_name from comments
left join (articles,categories) on (comments.article_id=articles.article_id and articles.category_id=categories.category_id)
where (comments.article_id in(1,2,3,4,5))
/*for duplicate comments*/ GROUP by comments.article_id /*for duplicate comments*/
ORDER BY `comments`.`comment_id` DESC limit 0 , 5
Please focus to comments_id
and article_id
columns
-sql-2: http://sqlfiddle.com/#!2/3ab6c1/2
![result 2](https://i.imgur.com/U7FGAxP.png)
it's ok, comments.article_id s grouped BUT "comments.comment_id desc" order is broken;
108
106
104
102
100
(must be 109 106 104 102 100)
I'm not an expert of mysql(I lost more than 3-4 hours)
-I need to show: "last(desc) 5 comments" in every category listing pages.
-I need to show: "last(desc) "1" comment for every article in(1,2,3,4,5 article_id s)"
(distinct and max shows same results 108 106 104 102 100
If I add group by comments.article_id
and remove order by comments.comment_id desc
, the list shows FIRST 1 comment of article -- I need to show LAST 1 comment of article)
Can any sql expert help me for this sql query ?