简体   繁体   English

使用PHP帮助MYSQL查询以构建博客存档导航菜单

[英]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: 然后循环浏览并运行以下查询,以获取该年/月博客文章的所有ID和标题:

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 编辑:忘记添加GROUP BY子句

EDIT 2: Forget the above. 编辑2:忘记以上。 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. 因此,建议的mysql_num_rows()毕竟还算不错。 :) :)

发送第一个查询( http://php.net/manual/en/function.mysql-num-rows.php )后,您可以通过php计算行数

You could do it using php count(); 您可以使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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