3

我有这个表,(sequence_No.)字段是null

ID        Name      age     sequence_No.
--        -----     ---     ------------
1         sara      20         
2         sara      20           
3         sara      20         
4         john      24         
5         john      24         
6         Hama      23         

我想将其更新为:

ID        Name      age     sequence_No.
--        -----     ---     ------------
1         sara      20         1
2         sara      20         2
3         sara      20         3
4         john      24         1
5         john      24         2
6         Hama      23         1

哪个查询可以做到这一点mysql

谢谢你

4

2 回答 2

4

ROW_NUMBER()您可以在 mysql 中使用相关子查询进行模拟。具有序列号的结果表将与表本身连接并更新sequence_No使用生成的数字的值。

UPDATE  tableName a
        INNER JOIN
        (
            SELECT  A.ID, 
                    (
                        SELECT  COUNT(*)
                        FROM    tableName c
                        WHERE   c.Name = a.Name AND
                                c.ID <= a.ID) AS sequence_No
            FROM    TableName a
        ) b ON a.ID = b.ID
SET     a.sequence_No = b.sequence_No
于 2013-09-04T08:53:18.630 回答
0
SELECT  ID, Name, age, sequence_No
FROM
        (
            select  ID,
                    Name,
                    age,
                    @sum := if(@nme = Name AND @acct = age, @sum ,0) + 1 sequence_No,
                    @nme := Name,
                    @acct := age
            from    TableName,
                    (select @nme := '', @sum := 0, @acct := '') vars
            order   by  Name, age
        ) s
ORDER   BY ID

或者你可以使用

SELECT 
ID,
Name,
age,
( 
CASE Name 
WHEN @curType 
THEN @curRow := @curRow + 1 
ELSE @curRow := 1 AND @curType := Name END
) + 1 AS sequence_No

FROM student, (SELECT @curRow := 0, @curType := '') r
ORDER BY  ID,NAME;

这虽然我还没有测试过,但你可以使用它来更新你的表格

于 2013-09-04T09:02:41.047 回答