gpt4 book ai didi

mysql - 获取特定年月内的记录

转载 作者:行者123 更新时间:2023-11-29 05:59:02 25 4
gpt4 key购买 nike

我有这个类方法来过滤属于特定年份和月份的记录

@posts = Post.filtered(params).published

def self.filtered (params)
unless params[:year].blank? && params[:month].blank?
year = params[:year].to_i
month = params[:month].to_i
return where(created_at: Date.new(year, month, 1)..Date.new(year, month, -1))
end
self
end

生成:

SELECT  `posts`.* 
FROM `posts`
WHERE (`posts`.`created_at` BETWEEN '2017-09-01' AND '2017-09-30') -- AND ...

rails c 中,我执行了 Post.pluck('id, created_at') 并得到了这些结果

SELECT id, created_at FROM `posts` ORDER BY created_at DESC
=> [[21, Fri, 06 Oct 2017 22:10:00 UTC +00:00],
[22, Sat, 30 Sep 2017 22:10:00 UTC +00:00], # September records
[7, Fri, 08 Sep 2017 19:48:14 UTC +00:00], # is where I get wrong number of records
[4, Tue, 29 Aug 2017 20:55:19 UTC +00:00],
[9, Wed, 16 Aug 2017 02:32:24 UTC +00:00],
[19, Tue, 15 Aug 2017 09:57:58 UTC +00:00],
[14, Mon, 14 Aug 2017 20:03:49 UTC +00:00],
[18, Mon, 14 Aug 2017 16:04:40 UTC +00:00],
[2, Sat, 12 Aug 2017 15:44:21 UTC +00:00],
[15, Sun, 06 Aug 2017 22:36:10 UTC +00:00],
[10, Sat, 22 Jul 2017 23:17:41 UTC +00:00],
[12, Fri, 21 Jul 2017 06:38:29 UTC +00:00],
[17, Sat, 15 Jul 2017 06:49:25 UTC +00:00],
[1, Fri, 14 Jul 2017 22:18:51 UTC +00:00],
[5, Tue, 11 Jul 2017 03:31:57 UTC +00:00],
[16, Sun, 09 Jul 2017 06:17:50 UTC +00:00],
[13, Sat, 08 Jul 2017 09:49:45 UTC +00:00],
[20, Sat, 08 Jul 2017 06:34:16 UTC +00:00],
[3, Thu, 06 Jul 2017 00:12:23 UTC +00:00],
[8, Sun, 02 Jul 2017 20:28:49 UTC +00:00],
[11, Fri, 23 Jun 2017 04:03:01 UTC +00:00],
[6, Wed, 21 Jun 2017 07:02:12 UTC +00:00]]

我尝试过按每个月的所有记录进行过滤,但我唯一弄错的是九月份的记录,在那里我只得到一条记录,而不是两条。

最佳答案

Select * from dual 
where created_at BETWEEN '2017-09-01' AND '2017-09-30'

可以读作:

Select * from dual 
where created_at >= '2017-09-01 00:00:00'
AND created_at <= '2017-09-30 00:00:00'

并且 2017 年 9 月 30 日 22:10:00 不小于或等于 2017-09-30 00:00:00...

编辑:

SQL Fiddle

MySQL 5.6 架构设置:

CREATE TABLE t
(`d` datetime)
;

INSERT INTO t
(`d`)
VALUES
('2017-09-30 00:00:00'),
('2017-09-30 02:02:02'),
('2017-09-20 12:12:12'),
('2017-09-08 21:21:21'),
('2017-09-08 00:00:00')
;

查询 1:

select date_format(d,'%Y-%m-%d %k:%i:%s') h from t
where d between '2017-09-08' and '2017-09-30'
order by d

Results :

|                   h |
|---------------------|
| 2017-09-08 0:00:00 |
| 2017-09-08 21:21:21 |
| 2017-09-20 12:12:12 |
| 2017-09-30 0:00:00 |

查询 2:

select date_format(d,'%Y-%m-%d %k:%i:%s') h from t
where d between '2017-09-08' and '2017-09-30 23:59:59'
order by d

Results :

|                   h |
|---------------------|
| 2017-09-08 0:00:00 |
| 2017-09-08 21:21:21 |
| 2017-09-20 12:12:12 |
| 2017-09-30 0:00:00 |
| 2017-09-30 2:02:02 |

关于mysql - 获取特定年月内的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46630745/

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