如何在 MySQL 中生成数据?

How to generate data in MySQL?(如何在 MySQL 中生成数据?)
本文介绍了如何在 MySQL 中生成数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 SQL:

SELECT 
  COUNT(id),
  CONCAT(YEAR(created_at), '-', MONTH(created_at), '-', DAY(created_at))
FROM my_table
GROUP BY YEAR(created_at), MONTH(created_at), DAY(created_at)

我希望即使在没有创建 ID 的日子里也能显示一行.现在,我在没有活动的日子里错过了很多日期.

I want a row to show up even for days where there was no ID created. Right now I'm missing a ton of dates for days where there was no activity.

关于如何更改此查询以执行此操作有任何想法吗?

Any thoughts on how to change this query to do that?

推荐答案

一个查询就搞定的方法:

The way to do it in one query:

SELECT COUNT(my_table.id) AS total,
 CONCAT(YEAR(dates.ddate), '-', MONTH(dates.ddate),  '-', DAY(dates.ddate))
FROM (
   -- Creates "on the fly" 65536 days beginning from 2000-01-01 (179 years)
   SELECT DATE_ADD("2000-01-01", INTERVAL (b1.b + b2.b + b3.b + b4.b + b5.b + b6.b + b7.b + b8.b + b9.b + b10.b + b11.b + b12.b + b13.b + b14.b + b15.b + b16.b) DAY) AS ddate FROM
   (SELECT 0 AS b UNION SELECT 1) b1,
   (SELECT 0 AS b UNION SELECT 2) b2,
   (SELECT 0 AS b UNION SELECT 4) b3,
   (SELECT 0 AS b UNION SELECT 8) b4,
   (SELECT 0 AS b UNION SELECT 16) b5,
   (SELECT 0 AS b UNION SELECT 32) b6,
   (SELECT 0 AS b UNION SELECT 64) b7,
   (SELECT 0 AS b UNION SELECT 128) b8,
   (SELECT 0 AS b UNION SELECT 256) b9,
   (SELECT 0 AS b UNION SELECT 512) b10,
   (SELECT 0 AS b UNION SELECT 1024) b11,
   (SELECT 0 AS b UNION SELECT 2048) b12,
   (SELECT 0 AS b UNION SELECT 4096) b13,
   (SELECT 0 AS b UNION SELECT 8192) b14,
   (SELECT 0 AS b UNION SELECT 16384) b15,
   (SELECT 0 AS b UNION SELECT 32768) b16
 ) dates
 LEFT JOIN my_table ON dates.ddate = my_table.created_at
 GROUP BY dates.ddate
 ORDER BY dates.ddate

仅当您要测试并且问题中没有指示my_table"时才需要下一个代码:

The next code is only necessary if you want to test and don't have the "my_table" indicated on the question:

create table `my_table` (
    `id` int (11),
    `created_at` date 
); 
insert into `my_table` (`id`, `created_at`) values('1','2000-01-01');
insert into `my_table` (`id`, `created_at`) values('2','2000-01-01');
insert into `my_table` (`id`, `created_at`) values('3','2000-01-01');
insert into `my_table` (`id`, `created_at`) values('4','2001-01-01');
insert into `my_table` (`id`, `created_at`) values('5','2100-06-06');

这篇关于如何在 MySQL 中生成数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)