gpt4 book ai didi

sql - 每月 Wordpress 帖子数

转载 作者:行者123 更新时间:2023-11-29 04:30:27 25 4
gpt4 key购买 nike

我需要在 Wordpress 中运行查询以获取每月有多少帖子(包括零)。

我的查询现在返回我要返回的内容的第一部分:

select
distinct date_format(post_date, '%y') "year",
date_format(post_date, '%b') "month",
from wp_posts
where post_type = 'post'
and post_status = 'publish'
group by date_format(post_date, '%y'), date_format(post_date, '%b')
order by date_format(post_date, '%y') desc, post_date

它返回如下内容:

|   year   |   month   |   count   |
------------------------------------
| 10 | Jan | 4 |
| 10 | Feb | 2 |
| 10 | Mar | 1 |
| 10 | Apr | 6 |
| 09 | Jan | 4 |
| 09 | Feb | 2 |

我需要返回类似的东西:

|   year   |   month   |   count   |
------------------------------------
| 10 | Jan | 4 |
| 10 | Feb | 2 |
| 10 | Mar | 1 |
| 10 | Apr | 6 |
| 10 | May | 0 |
| 10 | Jun | 0 |
| 10 | Jul | 0 |
| 10 | Aug | 0 |
| 10 | Sep | 0 |
| 10 | Oct | 0 |
| 10 | Nov | 0 |
| 10 | Dec | 0 |
| 09 | Jan | 4 |
| 09 | Feb | 2 |
| 09 | Mar | 0 |
| 09 | Apr | 0 |
| 09 | May | 0 |
| 09 | Jun | 0 |
| 09 | Jul | 0 |
| 09 | Aug | 0 |
| 09 | Sep | 0 |
| 09 | Oct | 0 |
| 09 | Nov | 0 |
| 09 | Dec | 0 |

我会在 Oracle 中使用 rownum,但我无法使用 MySQL 语法找出查询。非常感谢任何帮助。

最佳答案

这需要数字表技巧 -

  1. 创建一个名为 NUMBERS 的表:

    DROP TABLE IF EXISTS `example`.`numbers`;
    CREATE TABLE `example`.`numbers` (
    `id` int(10) unsigned NOT NULL auto_increment,
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
  2. 通过至少运行以下命令来填充表:

    INSERT INTO NUMBERS (id) VALUES (NULL)

这将允许您使用以下方法生成日期列表:

SELECT DATE(DATE_ADD('2009-01-01', INTERVAL n.id MONTH)) AS dt
FROM NUMBERS n

现在,您可以将当前查询加入到日期列表中:

   SELECT DATE_FORMAT(x.dt, '%y') "year",
DATE_FORMAT(x.dt, '%b') "month",
COUNT(*) AS count
FROM (SELECT DATE_ADD('2009-01-01', INTERVAL n.id MONTH) AS dt
FROM NUMBERS n) x
LEFT JOIN WP_POSTS wp ON MONTH(wp.post_date) = MONTH(x.dt)
AND YEAR(wp.post_date) = YEAR(x.dt)
AND wp.post_type = 'post'
AND wp.post_status = 'publish'
WHERE YEAR(x.dt) IN (2009, 2010)
GROUP BY DATE_FORMAT(x.dt, '%y'), DATE_FORMAT(x.dt, '%b')
ORDER BY DATE_FORMAT(x.dt, '%y') DESC, MONTH(x.dt)

关于sql - 每月 Wordpress 帖子数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3286000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com