SQL SELECT to get the first N positive integers

前端 未结 10 1358

I need to get a result set containing the first N positive integers. Is it possible to use only standard SQL SELECT statement to get them (without any count table provided)?

相关标签:
10条回答
  • 2020-11-30 13:16

    This may help

    To obtain a random integer R in the range i <= R < j, use the expression FLOOR(i + RAND() * (j – i)). For example, to obtain a random integer in the range the range 7 <= R < 12, you could use the following statement:

    SELECT FLOOR(7 + (RAND() * 5));

    0 讨论(0)
  • 2020-11-30 13:19

    Take a look at the following SO questions:

    • How to generate a range of numbers in Mysql
    • generate an integer sequence in MySQL

    Edit:

    Another aproach is to create a stored procedure that does that for you. PostgreSQL contains a function generate_series(start, stop) that does what you want.

    select * from generate_series(2,4);
     generate_series
    -----------------
                   2
                   3
                   4
    (3 rows)
    

    I'm not familar with MySQL but somthing like that should be easy to implement, if you are okay with SPs. This site shows an implemetation.

    0 讨论(0)
  • 2020-11-30 13:20

    Weird solution, but...

    SELECT 1 UNION SELECT 2 UNION SELECT 3....
    
    0 讨论(0)
  • 2020-11-30 13:23

    Assuming you mean retrieve them from a table, here N is 10, assuming intcolumn is the column with numbers in it.

    SELECT intcolumn FROM numbers WHERE intcolumn > 0 LIMIT 10
    

    Edit: In case you were actually looking to get the mathematical set of positive numbers without a table, I would reconsider, it can be intensive (depending on the implementation). Commonly accepted practice seems to be to create a lookup table full of numbers, and then use the above query.

    0 讨论(0)
提交回复
热议问题