2016-05-13 32 views
0

如何选择两个日期之间的所有日期?如何在mysql中选择两年之间的每一年?

我的表是这样的:

CREATE TABLE IF NOT EXISTS `product_modification` ( 
     `id_product_modification` int(11) NOT NULL AUTO_INCREMENT, 
     `id_category` int(11) NOT NULL, 
     `id_sub_category` int(11) NOT NULL, 
     `name` varchar(255) NOT NULL, 
     `start_production_year` int(8) DEFAULT NULL, 
     `end_production_year` int(8) DEFAULT NULL, 
     `id_product_type` int(8) NOT NULL, 
     PRIMARY KEY (`id_product_modification`) 
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8; 

    INSERT INTO `product_modification` (`id_product_modification`, `id_category`, `id_sub_category`, `name`, `start_production_year`, `end_production_year`, `id_product_type`) VALUES 
    (1, 1, 1, 'product_1', 2003, 2006, 1), 
    (2, 1, 1, 'product_2', 2009, 2011, 1), 
    (3, 1, 1, 'product_3', 2014, 2016, 1); 

我想显示一排这样的:

id_product_modification | YEAR 
------------------------------------------ 
        1 | 2003 
        1 | 2004 
        1 | 2005 
        1 | 2006 
        2 | 2009 
        2 | 2010 
        2 | 2011 
        3 | 2014 
        3 | 2015 
        3 | 2016 

有一个内置在这个功能呢?有没有办法让函数返回多行?

它必须是一个函数,因为我需要在其他SQL语句中使用它。

回答

0

你可以使用一个存储过程,一个游标

对于每一行的表走start_production_year,end_production_year和id_product_modification 将您的start_production_year一个时间变量,并打开一个循环。 在每个循环中,将您的时间变量增加一年,然后将生成的年份和id_product_modification插入到您的结果表中 一旦您的时间变量达到end_production_year,就停止循环。你的光标关闭后,返回表

编辑:刚才注意到你问了一个函数。我非常确定函数不能在MySQL上返回表格

+0

你能写代码吗我是新手 – Mil

0

这里没有内置函数,但可以使用下面的函数。它可以在100年的范围内工作,如果你需要更多的话,你必须在IntBase之内添加另一个连接,以使它成为y3k就绪。

select pm.id_product_modification, YearBase.yyyy 
from product_modification pm 
join (
select n + (select min(start_production_year) from product_modification) as yyyy 
from 
( 
    SELECT INTPART1.n + INTPART2.n * 10 as n 
    FROM 
    (SELECT 0 as n UNION SELECT 1 union select 2 union select 3 union select 4 union select 5 
    union select 6 union select 7 union select 8 union select 9) INTPART1 
    cross join 
    (SELECT 0 as n UNION SELECT 1 union select 2 union select 3 union select 4 union select 5 
    union select 6 union select 7 union select 8 union select 9) INTPART2 
) as IntBase 
) as YearBase 
on YearBase.yyyy >= pm.start_production_year and YearBase.yyyy <= pm.end_production_year; 
相关问题