Mysql按组递增列值

时间:2015-03-12 21:49:47

标签: mysql

想要在同一个parentid的组之间增加列。请参阅以下问题:

ID    Name    Parent   Pos
================================
1     Alex       1      0
2     Mary       1      0
3     John       1      0
4     Doe        2      0
5     Bob        2      0
6     Kate       2      0

预期结果

ID    Name    Parent   Pos
================================
1     Alex       1      1
2     Mary       1      2
3     John       1      3
4     Doe        2      1
5     Bob        2      2
6     Kate       2      3

我会使用两个查询来执行父项的选择不同的值,然后在集合中执行循环和更新,但我觉得有一种更有效的方法! !

3 个答案:

答案 0 :(得分:2)

这些问题可以通过排名功能轻松解决。由于mysql不支持排名功能,我们可以选择其他方式。 检查此查询

- 密集等级

SELECT 
  Id,
  NAME,
  Parent,
  Pos
  , case when @previousParent = rankTab.Parent THEN @runningGroup := @runningGroup + 1
         else @runningGroup := 1 AND @previousParent := rankTab.Parent 
    END as denseRank

FROM
  inc_col_val_by_group AS rankTab,
    (SELECT @runningGroup := 0) AS b 
  , (select @previousParent := 0 ) as prev
ORDER BY rankTab.Parent -- order by Parent 

--  

    -- -- below are the create table & insert the given records script
    -- create the table
    CREATE TABLE inc_col_val_by_group
    (Id INT
    , NAME CHAR(10)
    , Parent INT
    , Pos INT
    )

    -- insert some records
    INSERT INTO inc_col_val_by_group(Id, NAME, Parent, Pos)
    VALUES
    (1, 'Alex', 1, 0)
    , (1, 'Mary', 1, 0)
    , (3, 'John', 1, 0)
    , (4, 'Doe', 2, 0)
    , (5, 'Bob', 2, 0)
    , (6, 'Kate', 2, 0)

答案 1 :(得分:0)

最有效的方法是使用变量:

select t.*,
       (@rn := if(@p = parent, @p + 1,
                  if(@p := parent, 1, 1)
                 )
       ) as pos
from table t cross join
     (select @p := 0, @rn := 0) init
order by parent, id;

答案 2 :(得分:0)

SET @posn:=0;
SET @pid:=0;

SELECT  IF(@pid=k.parentid,@posn:=@posn+1,@posn:=1) pos,@pid:=k.parentid pid, k.* 
FROM kids k 
ORDER BY parentid