How to select multiple rows filled with constants?

后端 未结 15 1059
夕颜
夕颜 2020-11-29 17:08

Selecting constants without referring to a table is perfectly legal in an SQL statement:

SELECT 1, 2, 3

The result set that the latter retu

15条回答
  •  不知归路
    2020-11-29 17:26

    In PostgreSQL, you can do:

    SELECT  *
    FROM    (
            VALUES
            (1, 2),
            (3, 4)
            ) AS q (col1, col2)
    

    In other systems, just use UNION ALL:

    SELECT  1 AS col1, 2 AS col2
    -- FROM    dual
    -- uncomment the line above if in Oracle
    UNION ALL
    SELECT  3 AS col1, 3 AS col2
    -- FROM    dual
    -- uncomment the line above if in Oracle
    

    In Oracle, SQL Server and PostgreSQL, you also can generate recordsets of arbitrary number of rows (providable with an external variable):

    SELECT  level
    FROM    dual
    CONNECT BY
            level <= :n
    

    in Oracle,

    WITH    q (l) AS
            (
            SELECT  1
            UNION ALL
            SELECT  l + 1
            FROM    q
            WHERE   l < @n
            )
    SELECT  l
    FROM    q
    -- OPTION (MAXRECURSION 0)
    -- uncomment line above if @n >= 100
    

    in SQL Server,

    SELECT  l
    FROM    generate_series(1, $n) l
    

    in PostgreSQL.

提交回复
热议问题