<分区>
我应该如何在最后一行更正的行之间平均拆分数字。假设数字是 100,则有 11 行。我将不得不在最后一行添加更正。 注意:不一定是最后一行,只要一行包括更正即可
从表中选择成本/计数
除了将更正添加到最后一行之外,将起作用。
有什么建议吗?
<分区>
我应该如何在最后一行更正的行之间平均拆分数字。假设数字是 100,则有 11 行。我将不得不在最后一行添加更正。 注意:不一定是最后一行,只要一行包括更正即可
从表中选择成本/计数
除了将更正添加到最后一行之外,将起作用。
有什么建议吗?
最佳答案
您可以使用简单的子查询来完成此操作。例如
select floor(100 / (select count(*) from f)) as number_between_row_count;
然后您可以设置一个用户变量并更新最后一行,例如;
set @number_between_row_count = 0;
select @number_between_row_count:=floor(100 / (select count(*) from f));
update f set bar = @number_between_row_count+1 order by id desc limit 1;
update f set bar = @number_between_row_count where bar is null;
我们的用户变量将保存计算(即:(100/5) = 20),因此将写入 20。
http://dev.mysql.com/doc/refman/5.7/en/user-variables.html
例如,我们有下表;
CREATE TABLE `33566497` (
`number` int(11) DEFAULT NULL,
`t` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('1', NULL);
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('2', NULL);
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('3', NULL);
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('4', NULL);
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('5', NULL);
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('6', NULL);
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('7', NULL);
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('8', NULL);
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('9', NULL);
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('10', NULL);
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('11', NULL);
我们有 11 条记录。前 10 条记录需要 t = 9
,最后一条记录需要 t = 10
,然后我们运行;
set @number_between_row_count = 0;
select @number_between_row_count:=floor(100 / (select count(*) from `33566497`)); #calc the number (and round down so it's a whole number)
update `33566497` set t = @number_between_row_count+1 order by number desc limit 1; #update the last record to number + 1 because we need 10, not 9
update `33566497` set t = @number_between_row_count where t is null; #set the rest to 9
关于mysql - 行之间的sql分割数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33566497/