views:

51

answers:

1

I have a database table that contains blog posts. I want to show on the homepage one (or more) post for each category, ordering by date, for example.

So my posts table looks like this: id | title | description | cat | filename | date

How would I create such a query? I've thought to use group-by or a subselect but I'm not sure if it's a good thing for performance... the table has a large number of records.

+2  A: 

MySQL doesn't support analytic functions (ROW_NUMBER, RANK, DENSE_RANK, NTILE...), but you can emulate the functionality with variables.

If you want the N most recent blog posts:

SELECT x.id,
       x.title,
       x.description,
       x.cat,
       x.filename,
       x.date
  FROM (SELECT bp.id,
               bp.title,
               bp.description,
               bp.cat,
               bp.filename,
               bp.date,
               CASE 
                 WHEN bp.cat = @category THEN @rownum := @rownum + 1
                 ELSE @rownum := 1
               END AS rank,
               @category := bp.cat
          FROM BLOG_POSTS bp
          JOIN (SELECT @rownum := 0, @category := NULL) r
      ORDER BY bp.cat, bp.date DESC) x
 WHERE x.rank <= N

If you want rank of 1 to be the earliest blog post, change the ORDER BY to:

ORDER BY bp.cat, bp.date
OMG Ponies
@OMG Ponies: thank you soo much... i would never get thru this!
Luciano
@Mark Byers: thank you too! so, i need to add something like this? ORDER BY x.date DESC
Luciano