Help with MYSQL query using PHP to build a blog archive navigation menu
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 `开发者_如何学Cdate` 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!
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. :)
You can count the rows via php after sending the first query (http://php.net/manual/en/function.mysql-num-rows.php)
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
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)
精彩评论