MYSQL行号插入表中

时间:2014-07-10 18:48:25

标签: mysql numbers row

我想找到分组的行号并插入表格以进一步查询。 这是我提出的代码,但它不起作用。我的意思是插入不单独执行查询。请建议解决。我试图将此代码放在存储过程中,但这也不起作用。返回的错误是Subquery返回超过1行。

set @type ='';
set @row_number =1;

insert into newtable(type,actualdeparturetime,actualarrivaltime,dummy_1,dummy_2,row_number)
select type, actualdeparturetime,actualarrivaltime,
@row_number:=if(@type=type,@row_number+1,1) as dummy_1,
@type := type as dummy_2,
@row_number as row_number
FROM sourcetable f
where actualarrivaltime<> '0000-00-00 00:00:00' 
AND actualarrivaltime > (now()-INTERVAL 1 MONTH)
order by type ; 

1 个答案:

答案 0 :(得分:0)

这是您的查询,重写以便变量初始化在from子句中:

insert into newtable(type, actualdeparturetime, actualarrivaltime,
                     dummy_1, dummy_2, row_number
                    )
    select type, actualdeparturetime, actualarrivaltime,
           @row_number := if(@type=type, @row_number+1, 1) as dummy_1,
           @type := type as dummy_2,
           @row_number as row_number
    from sourcetable f cross join
         (select @type := '',  @row_number := 1) vars
    where actualarrivaltime <> '0000-00-00 00:00:00' AND
          actualarrivaltime > (now()-INTERVAL 1 MONTH)
    order by type ; 

我没有看到任何子查询,因此我不知道该特定错误是如何发生的。

如果不需要dummy_1dummy_2,您可以将其写为:

insert into newtable(type, actualdeparturetime, actualarrivaltime, row_number
                    )
    select type, actualdeparturetime, actualarrivaltime,
           @row_number := if(@type = type, @row_number+1, if(@type := type is null, 1, 1)) as row_number,
    from sourcetable f cross join
         (select @type := '',  @row_number := 1) vars
    where actualarrivaltime <> '0000-00-00 00:00:00' AND
          actualarrivaltime > (now()-INTERVAL 1 MONTH)
    order by type ; 

这会将@type的分配移至else的{​​{1}}子句。此版本也更安全,因为MySQL不保证if表达式的处理顺序。如果它们以相反的顺序处理,那么变量将全部搞砸在原始版本中。