如何在 MySQL 中生成数据? [英] How to generate data in MySQL?

查看:51
本文介绍了如何在 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 中生成数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆