gpt4 book ai didi

mysql - 在 MySQL 中生成统计信息

转载 作者:行者123 更新时间:2023-11-29 09:01:39 27 4
gpt4 key购买 nike

我有一个包含帖子的表格,我想生成一个图表,显示过去 30 分钟以及之前的最后 30 分钟等发布的帖子数量。帖子由其 post_handler 和 post_status 选择。

表结构如下所示。

CREATE TABLE IF NOT EXISTS `posts` (
`post_title` varchar(255) NOT NULL,
`post_content` text NOT NULL,
`post_date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`post_handler` varchar(255) NOT NULL,
`post_status` tinyint(4) NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
KEY `post_status` (`post_status`),
KEY `post_status_2` (`post_status`,`id`),
KEY `post_handler` (`post_handler`),
KEY `post_date_added` (`post_date_added`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2300131 ;

我想要收到的结果,在 post_date_add 之后排序。

period_start period_end  posts
2011-12-06 19:23:44 2011-12-06 19:53:44 10
2011-12-06 19:53:44 2011-12-06 20:23:44 39
2011-12-06 20:23:44 2011-12-06 20:53:44 40

现在,我使用的解决方案必须多次运行此查询,然后将数据从 PHP 脚本插入到另一个表中。

SELECT COUNT(*) FROM posts WHERE post_handler = 'test' AND post_status = 1 AND post_date_added BETWEEN '2011-12-06 19:23:44' AND '2011-12-06 19:53:44'

您知道其他解决方案吗?有没有一种方法可以运行一个查询,同时将结果插入数据库,所有这些都在一个查询中?

最佳答案

按独特的时间参数(例如小时、分钟、天或其他)进行分组相当容易。如果您想按小时对其进行分组,可能的查询可能如下所示:

SELECT DATE_FORMAT(post_date_added,"%Y-%m-%d %H") AS "_Date", 
COUNT(*)
FROM posts
WHERE post_handler = 'test'
AND post_status = 1
GROUP BY _Date;

(使用您选择的 mysql 查询工具运行此命令以查看输出)。

但是,如果您想以 30 分钟作为小组的基础,则 SQL 部分会变得更加棘手。对于这个特殊目的,由于您只需分为两个不同的子集,因此可以使用这种方法:

SELECT DATE_FORMAT(post_date_added,"%Y-%m-%d %H") AS "_Date", 
"00" AS "semihour",
COUNT(*)
FROM posts
WHERE post_handler = 'test'
AND DATE_FORMAT(post_date_added,"%i") < 30
AND post_status = 1
GROUP BY _Date
UNION
SELECT DATE_FORMAT(post_date_added,"%Y-%m-%d %H") AS "_Date",
"30" AS "semihour",
COUNT(*)
FROM posts
WHERE post_handler = 'test'
AND DATE_FORMAT(post_date_added,"%i") >= 30
AND post_status = 1
GROUP BY _Date;

再次使用您选择的 mysql 查询工具运行此命令以查看输出。您也可以使用 CASEIF 等添加数学区别,但就我个人而言,我会按小时或分钟分组,只是为了让 SQL 部分更容易。

要将这些数字直接添加到图形数据库中,请使用以下语法:

INSERT INTO yourtable (yourfields)
SELECT ...

有关此内容的更多详细信息,请参阅 here在 MySQL 文档中。

关于mysql - 在 MySQL 中生成统计信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8406295/

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