思路:
······确定该年有多少天
······建立表temp_num,存储0,1,...,直到该年的天数-1
······利用temp_num查询出该年的每一天
······利用dayname函数设定条件,只查询出周五的日期
假设查询‘1990-10-30’所在年份的所有星期五,首先计算1990有多少天:
mysql> set @num_day = abs(
-> datediff(
-> date_add('1990-10-30',interval -dayofyear('1990-10-30') day),
-> date_add(
-> date_add('1990-10-30',interval -dayofyear('1990-10-30') day),
-> interval 1 year)
-> )
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> select @num_day;
+----------+
| @num_day |
+----------+
| 365 |
+----------+
1 row in set (0.00 sec)
稍微解释一下逻辑
date_add('1990-10-30',interval -dayofyear('1990-10-30') day)查询到的是1989年的最后一天,用1990-10-30减去当前日期位于全年的第几天即可;
在获取了该年的第一天之后,在此基础上加一年,即可获取1990年的最后一天
date_add('1990-10-30',interval -dayofyear('1990-10-30') day),interval 1 year)
对这两个日期求天数差,即可获取1990年有多少天;
下面开始建表temp_num,建立一个存储过程,像表中插入1,2,...,num_day+1 个记录
mysql> create table temp_num(num int);
Query OK, 0 rows affected (0.03 sec)
mysql> delimiter $$
mysql> create procedure auto_num(in num_day int)
-> begin
-> declare i int;
-> set i=1;
-> while i<num_day+1 do
-> insert into temp_num(num) values(i);
-> set i=i+1;
-> end while;
-> end$$
Query OK, 0 rows affected (0.01 sec)
mysql> delimiter ;
mysql> call auto_num(@num_day);
Query OK, 1 row affected (1.20 sec)
将1989年的最后一天逐一与temp_num中的数值相加,即可查询1990年的每个日期了。
mysql> select num,
-> date_add(
-> date_add('1990-10-30',interval -dayofyear('1990-10-30') day),
-> interval num day
-> ) as 1990_day
-> from temp_num limit 10;
+------+------------+
| num | 1990_day |
+------+------------+
| 1 | 1990-01-01 |
| 2 | 1990-01-02 |
| 3 | 1990-01-03 |
| 4 | 1990-01-04 |
| 5 | 1990-01-05 |
| 6 | 1990-01-06 |
| 7 | 1990-01-07 |
| 8 | 1990-01-08 |
| 9 | 1990-01-09 |
| 10 | 1990-01-10 |
+------+------------+
10 rows in set (0.00 sec)
mysql> select num,
-> date_add(
-> date_add('1990-10-30',interval -dayofyear('1990-10-30') day),
-> interval num day
-> ) as 1990_day
-> from temp_num limit 10 offset 360;
+------+------------+
| num | 1990_day |
+------+------------+
| 361 | 1990-12-27 |
| 362 | 1990-12-28 |
| 363 | 1990-12-29 |
| 364 | 1990-12-30 |
| 365 | 1990-12-31 |
+------+------------+
5 rows in set (0.00 sec)
利用dayname函数,加一个限制条件便可查询到为周五的日期了。
mysql> select num,
-> date_add(
-> date_add('1990-10-30',interval -dayofyear('1990-10-30') day),
-> interval num day
-> ) as 1990_day
-> from temp_num
-> having dayname(1990_day)='Friday'
-> limit 10;
+------+------------+
| num | 1990_day |
+------+------------+
| 5 | 1990-01-05 |
| 12 | 1990-01-12 |
| 19 | 1990-01-19 |
| 26 | 1990-01-26 |
| 33 | 1990-02-02 |
| 40 | 1990-02-09 |
| 47 | 1990-02-16 |
| 54 | 1990-02-23 |
| 61 | 1990-03-02 |
| 68 | 1990-03-09 |
+------+------------+
10 rows in set (0.00 sec)