views:

46

answers:

4

I am building a blog archive navigation menu. Currently I run a query to get all the years and months. Then I loop through and run the following query to get all id's and titles of that year/months blog posts:

SELECT `id`, `title` 
FROM `news` 
WHERE YEAR(`date`) = "2010" AND MONTH(`date`) = "03" 
ORDER BY `date` DESC

After that, to count the amount of posts for that month I am running a very similar query:

SELECT COUNT(*) as `count` 
FROM `news` 
WHERE YEAR(`date`) = "2010" AND MONTH(`date`) = "03"

The year and month are dynamic of course.

Is there any way to avoid having to run two separate queries?

Thanks ahead of time!

A: 

You can count the rows via php after sending the first query (http://php.net/manual/en/function.mysql-num-rows.php)

Tim
duh. you right. sometimes i just tend to overthink stuff ;)
Roeland
A: 

You could do it using php count(); If your db Implements this methods :

echo count($this->db->fetch_array($q));

it will be easy to get know how many items there are

streetparade
A: 

Can't you do all of this in one shot?!


SELECT COUNT(id) as count, MONTH(date) as month, YEAR(date) as year 
FROM news 
GROUP BY MONTH(date), YEAR(date)

mmattax
A: 

What's wrong with:

SELECT `id`, `title`, count(*) AS `count` 
FROM `news` 
WHERE YEAR(`date`) = "2010" AND MONTH(`date`) = "03" 
GROUP BY ( `id` ) #assuming id is unique
ORDER BY `date` DESC

?

EDIT: Forgot to add GROUP BY clause

EDIT 2: Forget the above. That was obviously not correct. This will do the trick, though it may be concidered not very elegant:

SELECT
    `id`,
    `title`,
    ( SELECT
          count(*)
      FROM
          `news`
      WHERE
          YEAR(`date`) = "2010" AND 
          MONTH(`date`) = "01" ) as `count`
FROM
    `news` 
WHERE
    YEAR(`date`) = "2010" AND
    MONTH(`date`) = "01"
ORDER BY
    `date` DESC

So maybe the suggested mysql_num_rows() isn't so bad after all. :)

fireeyedboy
when i add this , it returns '1' as the result for every row instead of in the case of 3 blog posts being return, it would show each record, each with the count value being 1.
Roeland
ughh, sorry, you are right of course. :( I'll update with another (not so elegant perhaps) solution. It uses a subquery.
fireeyedboy
cool. subquery would also def work. i not very good with the subqueries yet.. so i generally dont even think of that route.
Roeland