Generate an integer sequence in MySQL

前端 未结 16 2705
南旧
南旧 2020-11-22 06:47

I need to do a join with a table/result-set/whatever that has the integers n to m inclusive. Is there a trivial way to get that without just buildi

16条回答
  •  礼貌的吻别
    2020-11-22 07:29

    Here is a compact binary version of the technique used in other answers here:

    select ((((((b7.0 << 1 | b6.0) << 1 | b5.0) << 1 | b4.0) 
                      << 1 | b3.0) << 1 | b2.0) << 1 | b1.0) << 1 | b0.0 as n
    from (select 0 union all select 1) as b0,
         (select 0 union all select 1) as b1,
         (select 0 union all select 1) as b2,
         (select 0 union all select 1) as b3,
         (select 0 union all select 1) as b4,
         (select 0 union all select 1) as b5,
         (select 0 union all select 1) as b6,
         (select 0 union all select 1) as b7
    

    There are no unique or sorting phases, no string to number conversion, no arithmetic operations, and each dummy table only has 2 rows, so it should be pretty fast.

    This version uses 8 "bits" so it counts from 0 to 255, but you can easily tweak that.

提交回复
热议问题