How to select several hardcoded SQL rows?

前端 未结 8 1550
囚心锁ツ
囚心锁ツ 2020-12-28 11:55

If you execute this query

SELECT \'test-a1\' AS name1, \'test-a2\' AS name2

the result will be a one row-selection with two columns having

相关标签:
8条回答
  • 2020-12-28 12:06

    In MySQL you could use UNION like this:

    SELECT * from 
        (SELECT 2006 AS year UNION
         SELECT 2007 AS year UNION
         SELECT 2008 AS year UNION
        ) AS years
    
    0 讨论(0)
  • 2020-12-28 12:20

    I'd love to hear is anyone has a better solution. In the past I've used this:

    Select top 3 'Hardcode'
    from tableWithLotsOfRows
    

    Would you mind switching abc, with 123?

    select top 3 
        'test-A'+convert(varchar, row_number() over (order by PrimaryKey)),
        'test-B'+convert(varchar, row_number() over (order by PrimaryKey))
    from tableWithLotsOfRows
    

    that should return something like:

    TestA1, Test-B1
    TestA2, Test-B2
    TestA3, Test-B3
    
    0 讨论(0)
  • 2020-12-28 12:20

    As of MySQL 8.0.19, it is possible to do

    SELECT
        column_0 AS name1,
        column_1 AS name2
    FROM
        (VALUES
            ROW('test-a1','test-a2'),
            ROW('test-b1','test-b2'),
            ROW('test-c1','test-c2')
        ) AS hardcodedNames
    

    Which returns

    name1   name2
    ==================
    test-a1 test-a2
    test-b1 test-b2
    test-c1 test-c2
    

    A note on column names

    The columns of the table output from VALUES have the implicitly named columns column_0, column_1, column_2, and so on, always beginning with 0.

    Documentation here: https://dev.mysql.com/doc/refman/8.0/en/values.html.

    0 讨论(0)
  • 2020-12-28 12:21

    Extending the answer of @openshac for oracle, as the below mentioned code works for oracle:

    SELECT 'test-a1' AS name1, 'test-a2' AS name2 from dual 
    UNION ALL 
    SELECT 'test-b1', 'test-b2' from dual
    UNION ALL 
    SELECT 'test-c1', 'test-c2' from dual
    
    0 讨论(0)
  • 2020-12-28 12:22

    UNION ALL is the best bet. It's faster than UNION and you will have mutually exclusive rows.

    0 讨论(0)
  • 2020-12-28 12:22
    SELECT 'test-a1' AS name1, 'test-a2' AS name2 
    UNION ALL 
    SELECT 'test-b1', 'test-b2'
    UNION ALL 
    SELECT 'test-c1', 'test-c2'
    
    0 讨论(0)
提交回复
热议问题