0

Am trying to get the latest post from each category of post ordered by the date, i tried this but its not giving the latest post from the table and when i use 'order by' before 'group by', the post are not ordered by date using mysql.

SELECT post_id, category, author_id, title, article, time FROM (SELECT * FROM blog_post GROUP BY category LIMIT 0,5 ) AS timePost ORDER BY time DESC

SELECT post_id, category, author_id, title, article, time FROM (SELECT * FROM blog_post ORDER BY date LIMIT 0,5 ) AS timePost GROUP BY category

cozmik05
  • 477
  • 5
  • 13

3 Answers3

1

You can do self join.

   SELECT T1.`post_id`,
           T1.`category`,
            T1.`author_id`,
             T1.`title`, 
             T1.`article`,
              T1.`time` 
    FROM
            blog_post T1
            INNER JOIN
            (SELECT MAX(`time`) AS `time`,`category` FROM blog_post GROUP BY category) T2
         ON T1.`category` = T2.`category` AND T1.`time` = T2.`time`
  ORDER BY T1.`time` DESC

Hope this helps.

Subin Chalil
  • 3,531
  • 2
  • 24
  • 38
0

IN MS SQL as your question is not clear as per my assumption

SELECT post_id, category, author_id, title, article, time
FROM blog_post t
WHERE 
 t.post_id=(SELECT TOP 1 post_id
          FROM Table t2
          WHERE 
           t.post_id=t2.post_id
          ORDER BY time DESC)
mohan111
  • 8,633
  • 4
  • 28
  • 55
-1

This seem to have work... i dont know how efficient it is though

SELECT post_id, category, author_id, title, article, time FROM (SELECT * FROM blog_post ORDER BY time DESC ) AS timePost GROUP BY category ORDER BY time DESC

cozmik05
  • 477
  • 5
  • 13