mysql - 如何在mysql中选择两年之间的每一年?

标签 mysql

如何选择两个日期之间的所有日期?

我的 table 是这样的:

    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 语句中使用它。

最佳答案

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

对于表中的每一行,获取开始生产年、结束生产年和 id_product_modification 将 start_product_year 分配给一个时间变量并打开一个循环。 在每个循环中,将时间变量增加一年,然后将结果年份和 id_product_modification 插入到结果表中 一旦时间变量达到 end_product_year,就停止循环。光标关闭后,返回表格

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

关于mysql - 如何在mysql中选择两年之间的每一年?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37213989/

相关文章:

php - Drupal php 查询不适用于某些单词

php - mysqli_query SELECT FROM WHERE [部分匹配]?

mysql - NodeJS 数据库(mysql)连接与事务管理

java - 单击按钮时,我在数据库中添加了一个对象(通过 struts 2)。但不是同时反射(reflect)

php - 根据MySQL数据库中的股票随机生成数字

mysql - SQL查询连接多个具有一对多关系的表

mysql - UNION 查询中的订单字段

python - 将包含字典列表中两个不同值的相同键的字典的 json 列表中的值插入到 MYSQL 数据库

php - 在 Codeigniter 中将事件记录与标准 SQL 查询混合

mysql - 将默认的 MYSQL JSON 值设置为 `{}` 还是 `NULL` 更好?