每10行自动递增


auto increment every 10 rows

我使用的是PHP。我将在数据库中创建一个具有值的列,例如1。我想把这个值设置为每次经过10行时自动递增:

换句话说:

1st row will have the value = 1
2nd row will have the value = 1
........
........
10th row will have the value = 1 
11th row the value will auto increment and change to be = to 2

以下是的解决方案

假设您有一个名为table1的表,该表具有以下结构

CREATE TABLE `table1` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(50) NOT NULL DEFAULT '0',
    PRIMARY KEY (`id`)
)

注意,id列是自动递增

以下查询将给您想要的结果

select a.id,FLOOR((a.id-1)/10)+1 as calculated_value from table1 a

在结果中,calculated_value将为您提供结果。

如果您感兴趣,请提供一些附加信息

假设您担心使用自动递增列进行计算是有风险的,那么您可以使用以下

    SELECT t.id,t.name ,(@num:=@num+1) AS i,FLOOR((@num-1)/10)+1 
as calculated_value  FROM table1 t CROSS JOIN (SELECT @num:=0) AS 
dummy ORDER BY id;