查询中的MySQL子位置计数器

时间:2011-09-26 20:04:19

标签: mysql sql large-data

我需要获取一个记录集,其中我每60个记录填充字段level1,这意味着我需要以这种方式填充level1字段:

  • on pos = 1且pos = 60,level1 = 1
  • on pos = 61 and pos = 120 with level1 = 2
  • on pos = 121 and pos = 180 with level1 = 3

... 然后:如果我要说630条记录我必须为pos = 601和630 level1 = 10设置,因为我没有660条记录,第630条记录完成了这个级别。

有谁知道如何以干净的方式做到这一点?

SET @pos:=0; 
SET @posrel:=0;
SET @level1:=0;
SELECT id, member_id, member_name, pos, @posrel:=@posrel+1 AS posrel, @level1:=@level1+??? AS level1
FROM
(
  SELECT id, member_id, LEFT(member_name, LENGTH(member_name)-36) AS member_name, @pos:=@pos+1 AS pos FROM member_directory WHERE member_name_first= 'A'
) AS directory_listing
HAVING pos % 60 IN(0,1);

1 个答案:

答案 0 :(得分:1)

-- SET @pos:=0;   //Can be moved inside the query.
-- SET @posrel:=0; 
SELECT inner.*, posrel DIV 60 as level1 FROM (
  SELECT directory_listing.*, @posrel:=@posrel+1 AS posrel  AS level1
  FROM
  (
    SELECT 
      id
      , member_id
      , LEFT(member_name, LENGTH(member_name)-36) AS member_name_first
      , @pos:=@pos+1 AS pos 
    FROM member_directory
    CROSS JOIN (SELECT @pos:= 0) x1  
    WHERE member_name_first = 'A'
    AND directory_listing.pos < 120
  ) directory_listing
  CROSS JOIN (SELECT @posrel:= 0) x2
) inner

或者

-- SET @pos:=0;   //Can be moved inside the query.
-- SET @posrel:=0; 
SELECT inner.*, posrel DIV 60 as level1 FROM (
  SELECT directory_listing.*, @posrel:=@posrel+1 AS posrel  AS level1
  FROM
  (
    SELECT 
      id
      , member_id
      , LEFT(member_name, 1) AS member_name_first
      , @pos:=@pos+1 AS pos 
    FROM member_directory
    CROSS JOIN (SELECT @pos:= 0) x1  
    WHERE member_name LIKE 'A%'
    AND directory_listing.pos < 120
  ) directory_listing
  CROSS JOIN (SELECT @posrel:= 0) x2
) inner