SQL: Select a list of numbers from “nothing”

后端 未结 4 1267
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-02 01:24

What is a fast/readable way to SELECT a relation from \"nothing\" that contains a list of numbers. I want to define which numbers by setting a start and end value. I am usi

4条回答
  •  北海茫月
    2021-01-02 02:15

    Well in SQL server (and PostgreSQL) I would use recursive common table expression: SQL Server, PostgreSQL

    with recursive Numbers as (
        select 0 as Number
        union all
        select Number + 1
        from Numbers
        where Number < 4
    )
    select Number
    from Numbers
    

    SQL FIDDLE EXAMPLE

    But, as far as I know, there's no WITH in SQLite.

    So, the possible solutions could be

    • create a user defined function (this could be helpful)
    • create a table with numbers from 0 to max number you'll ever need, and then just select from it like this:

      select Number from Numbers where Number >= 0 and Number <= 4
      

提交回复
热议问题