How to select every YEAR between two year in mysql?

时间:2016-05-13 15:32:49

标签: mysql

How can I select all of the dates between two dates?

My table like this :

    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); 

I want to display a row like this :

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

Is there a built in function for this? Is there a way for a function to return multiple rows?

It has to be a function because I need to use it within other SQL statements.

2 个答案:

答案 0 :(得分:0)

您可以使用存储过程和光标

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

编辑:刚刚注意到你要求一个功能。我非常确定函数不能返回MySQL上的表

答案 1 :(得分:0)

没有内置功能,但您可以使用以下功能。它适用于100年的范围,如果您需要更多,您必须在IntBase内添加另一个连接以使其准备就绪。

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;