所以我将这些数据存储在mysql中:
| name | number | group |
-------------------------------
| godard | | 1 |
| gaylord| | 1 |
| linda | | 1 |
| demi | | 2 |
| micha | | 2 |
我想按组字段插入订单号。所以表格如下:
| name | number | group |
-------------------------------
| godard | 1 | 1 |
| gaylord| 2 | 1 |
| linda | 3 | 1 |
| demi | 1 | 2 |
| micha | 2 | 2 |
我可以在mysql中执行此操作:
答案 0 :(得分:0)
您可以使用以下查询来完成此操作。
SET @a = 1;
SET @past = '';
CREATE TEMPORARY TABLE IF NOT EXISTS `temp_test` (
`name` VARCHAR(50) NULL DEFAULT NULL,
`group` TINYINT(4) NULL DEFAULT NULL,
`number` TINYINT(4) NULL DEFAULT NULL
)
SELECT t.name as name, if(@past = t.`group`, @a:= @a + 1, @a:= 1) as
number, @past:= t.`group` as 'group'
FROM test t
ORDER BY t.`group`;
UPDATE test
INNER JOIN temp_test ON test.name = temp_test.name AND test.`group` = temp_test.`group` SET test.number = temp_test.number WHERE test.number IS NULL OR test.number = 0 OR test.number = '';
DROP TEMPORARY TABLE IF EXISTS temp_test;
答案 1 :(得分:0)
检查这个。
@row_num变量保存当前行号,@ pev_value变量保存分区的当前值。
UPDATE TEMP T join
(select o.Name,@row_num := IF(@prev_value=o.group,@row_num+1,1) AS Number
,@prev_value := o.group AS `Group`
from temp o ,
(SELECT @row_num := 1) x,
(SELECT @prev_value := '') y
)a on a.name=T.name and a.`group` =T.`group`
SET T.number = a.Number\\
select * from temp
OutPut:
如果您有任何问题或疑虑,请告知我们。