Problem Solution Discussion Generating Repeating Sequences

seq = dbh-selectrow_array SELECT LAST_INSERT_ID ; The single- row sequence- generat ion m echanism is revisit ed in Recipe 18.13 , where it serves as t he basis for im plem ent ing web page hit count ers.

11.18 Generating Repeating Sequences

11.18.1 Problem

You need t o creat e a sequence t hat cont ains cycles.

11.18.2 Solution

Generat e a sequence and produce t he cyclic elem ent s using division and t he m odulo operat or.

11.18.3 Discussion

Som e sequence- generat ion problem s require values t hat go t hrough cycles. Suppose youre m anufact uring it em s like pharm aceut ical product s or aut om obile part s, and you m ust be able t o t rack t hem by lot num ber if m anufact uring problem s are discovered lat er t hat require it em s sold wit hin a part icular lot t o be recalled. Suppose also t hat you pack and dist ribut e it em s 12 unit s t o a box and 6 boxes t o a case. I n t his sit uat ion, it em ident ifiers are t hree- part values: The unit num ber wit h a value from 1 t o 12 , t he box num ber wit h a value from 1 t o 6 , and a lot num ber wit h a value from 1 t o what ever t he highest case num ber happens t o be current ly . This it em - t racking problem appears t o require t hat you m aint ain t hree count ers, so you m ight t hink about generat ing t he next ident ifier value using an algorit hm like t his: retrieve most recently used case, box, and unit numbers unit = unit + 1 increment unit number if unit 12 need to start a new box? { unit = 1 go to first unit of next box box = box + 1 } if box 6 need to start a new case? { box = 1 go to first box of next case case = case + 1 } store new case, box, and unit numbers You could indeed im plem ent an algorit hm t hat way. On t he ot her hand, it s also possible sim ply t o assign each it em a sequence num ber ident ifier and derive t he corresponding case, box, and unit num bers from it . The ident ifier can com e from an AUTO_INCREMENT colum n or a single- row sequence generat or. The form ulas for det erm ining t he case, box, and unit num bers for any it em from it s sequence num ber look like t his: unit = seq - 1 12 + 1 box = int seq - 1 12 6 + 1 case = int seq - 16 12 + 1 The t able shown below illust rat es t he relat ionship bet ween som e sam ple sequence num bers and t he corresponding case, box, and unit num bers: seq case box unit 1 1 1 1 12 1 1 12 13 1 2 1 72 1 6 12 73 2 1 1 144 2 6 12

11.19 Numbering Query Output Rows Sequentially