根据两列之间的INT差异选择其他行

时间:2015-12-21 22:42:39

标签: mysql

我有一个结构如下的数据集:

Make|StartYear|EndYear
----------------------
AA  | 2000    | 2005
AB  | 1984    | 1989
AR  | 1965    | 1966
BC  | 1999    | 2000

“年”列目前存储为INT格式。我试图通过SELECT返回一个像这样结构化的数据集:

Make|StartYear|EndYear|Year
----------------------|------
AA  | 2000    | 2005  | 2000
AA  | 2000    | 2005  | 2001
AA  | 2000    | 2005  | 2002
AA  | 2000    | 2005  | 2003
AA  | 2000    | 2005  | 2004
AA  | 2000    | 2005  | 2005
AB  | 1984    | 1989  | 1984
----------------------------------
AB  | 1984    | 1989  | 1988
AB  | 1984    | 1989  | 1989

无论如何,这可以通过MySQL实现吗?

1 个答案:

答案 0 :(得分:1)

这里你去..我正在使用临时表..和SP。

CREATE DEFINER=`root`@`localhost` PROCEDURE `mytest`()
BEGIN


declare _make varchar(20);
declare _startyear int;
declare _endyear int;
DECLARE bDone INT;
DECLARE ioffset INT;

DECLARE curs CURSOR FOR  SELECT make, startyear, endyear  FROM test.maketable;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;

DROP TEMPORARY TABLE IF EXISTS tmpmake;
CREATE TEMPORARY TABLE tmpmake AS  
    SELECT make, startyear, endyear, startyear as theyear from test.maketable;


 OPEN curs;

  SET bDone = 0;
  REPEAT
    FETCH curs INTO _make,_startyear, _endyear;
    Set ioffset = 1;
    While (_startyear + ioffset <= _endyear and bDone = 0) do
      Insert into tmpmake values (_make,_startyear, _endyear, _startyear + ioffset);
      Set ioffset = ioffset + 1;
    end while;

  UNTIL bDone END REPEAT;

  CLOSE curs;
  SELECT * FROM tmpmake order by 1,4;
-- 
--  
END