简体   繁体   中英

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 `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!

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. :)

发送第一个查询( http://php.net/manual/en/function.mysql-num-rows.php )后,您可以通过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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM