我需要获取一个记录集,其中我每60个记录填充字段level1,这意味着我需要以这种方式填充level1字段:
... 然后:如果我要说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);
答案 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