最新消息:文章中包含代码时,请遵守代码高亮规范!

MySQL查询今天,本周,上周,本月,上个月,本季度,上季度,今年,去年的数据的sql[转载]

MySQL Alex 91浏览 1评论
现在假设有这样一张订单数据表:

CREATE TABLE `order` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `order_sn` varchar(50) CHARACTER SET utf8 NOT NULL DEFAULT '' COMMENT '订单编号,保证唯一',
  `create_at` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间',
  `success_at` int(11) NOT NULL DEFAULT '0' COMMENT '订单完成时间',
  `creator_id` varchar(50) CHARACTER SET utf8 NOT NULL DEFAULT '' COMMENT '订单创建人',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uni_sn` (`order_sn`),
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='订单表';

现在以如上表为例查询相关的数据:

查询今天所有已完成的订单编号:

SELECT `order_sn` FROM `order` WHERE YEARWEEK(FROM_UNIXTIME(success_at,'%Y-%m-%d')) = date_format(now(),'%Y-%m-%d');

查询当前这周所有已完成的订单编号:

SELECT `order_sn` FROM `order` WHERE YEARWEEK(FROM_UNIXTIME(success_at,'%Y-%m-%d')) = YEARWEEK(now());

查询上周所有已完成的订单编号:

SELECT `order_sn` FROM `order` WHERE YEARWEEK(FROM_UNIXTIME(success_at,'%Y-%m-%d')) = YEARWEEK(now())-1;

查询当前月份所有已完成的订单编号:

select `order_sn` from `order` where FROM_UNIXTIME(success_at,'%Y-%m')=date_format(now(),'%Y-%m');

查询上个月份所有已完成的订单编号:

select `order_sn` from `order` where FROM_UNIXTIME(success_at,'%Y-%m')=date_format(DATE_SUB(curdate(), INTERVAL 1 month),'%Y-%m');

查询距离当前现在6个月已完成的订单编号:

select `order_sn` from `order` where FROM_UNIXTIME(success_at,'%Y-%m-%d %H:%i:%s') between date_sub(now(),interval 6 month) and now();

查询本季度所有已完成的订单编号:

select `order_sn` from `order` where QUARTER(FROM_UNIXTIME(success_at,'%Y-%m-%d'))=QUARTER(now());

查询上季度所有已完成的订单编号:

select `order_sn` from `order` where QUARTER(FROM_UNIXTIME(success_at,'%Y-%m-%d'))=QUARTER(DATE_SUB(now(),interval 1 QUARTER));

查询本年所有已完成的订单编号:

select `order_sn` from `order` where YEAR(FROM_UNIXTIME(success_at,'%Y-%m-%d'))=YEAR(NOW());

查询上年所有已完成的订单编号:

select `order_sn` from `order` where year(FROM_UNIXTIME(success_at,'%Y-%m-%d'))=year(date_sub(now(),interval 1 year));

转载时请注明出处及相应链接,本文永久地址:http://blog.it985.com/22715.html


pay_weixin
pay_weixin
微信打赏
pay_weixin
支付宝打赏
感谢您对作者Alex的打赏,我们会更加努力!    如果您想成为作者,请点我

您必须 登录 才能发表评论!

网友最新评论 (1)

  1. Terry
    考虑下效率和索引的问题
    Terry2017-12-21 10:56