例如现在是八月,我想要一个选择查询,其结果如下:
+-----------+
| September |
+-----------+
| October |
+-----------+
| November |
+-----------+
| December |
+-----------+
| January |
+-----------+
| February |
+-----------+
| March |
+-----------+
| April |
+-----------+
| May |
+-----------+
| June |
+-----------+
| July |
+-----------+
| August |
+-----------+
此订单将在下个月更改。 抱歉,如果重复,我不知道要搜索的关键字是什么。
答案 0 :(得分:2)
您可以使用monthname()
获取日期的月份名称,并使用date_add()
从日期中减去月份。也就是说,您可以使用UNION ALL
和无表SELECT
来获取月的名称来构建查询,以获得所需的结果。
SELECT monthname(date_add(curdate(), interval -11 month))
UNION ALL
SELECT monthname(date_add(curdate(), interval -10 month))
...
UNION ALL
SELECT monthname(date_add(curdate(), interval -1 month))
UNION ALL
SELECT monthname(curdate());
编辑:
要使其更具动态性,您一次可以创建一个数字表。
CREATE TABLE integers
(i integer);
INSERT INTO integers
(i)
VALUES ...
(-11),
(-10),
...
(-1),
(0),
...;
然后您可以从该表中选择所需的范围,以建立月份列表。
SELECT monthname(date_add(curdate(), interval i month))
FROM integers
WHERE i >= -11
AND i <= 0
ORDER BY i;
答案 1 :(得分:0)
使用UNION ALL
即时创建月份行,或创建表并在其中插入记录。夫妇月份名称和月份编号。使用数字进行排序。如果要从下个月开始,请与当前月份进行比较:
select name
from
(
select 1 as num, monthname('2000-01-01') as name
union all
select 2 as num, monthname('2000-02-01') as name
union all
select 3 as num, monthname('2000-03-01') as name
union all
select 4 as num, monthname('2000-04-01') as name
union all
select 5 as num, monthname('2000-05-01') as name
union all
select 6 as num, monthname('2000-06-01') as name
union all
select 7 as num, monthname('2000-07-01') as name
union all
select 8 as num, monthname('2000-08-01') as name
union all
select 9 as num, monthname('2000-09-01') as name
union all
select 10 as num, monthname('2000-10-01') as name
union all
select 11 as num, monthname('2000-11-01') as name
union all
select 12 as num, monthname('2000-12-01') as name
) months
order by num <= month(current_date), num;
上个月的演示:http://rextester.com/NOYU32731
(这将根据数据库中的语言设置为您提供月份名称。因此,使用此查询时,法国的男孩将以与西班牙的女孩相同的语言查看月份名称。)