mysql-如何选择几个硬编码的SQL行?

如果执行此查询

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

结果将是具有两列的单行选择,这些列具有以下值:

test-a1, test-a2

如何修改上述查询,使其具有多行选择,例如

test-a1, test-a2
test-b1, test-b2
test-c1, test-c2

我知道如何使用UNION做到这一点,但我觉得存在一种更简单的方法。

PS。 很抱歉有这样一个基本问题,很难谷歌搜索。

Eugene asked 2020-07-31T02:04:58Z
7个解决方案
41 votes

Values关键字可以按以下方式使用。

select * from 
(values ('test-a1', 'test-a2'), ('test-b1', 'test-b2'), ('test-c1', 'test-c2')) x(col1, col2)
Muthu answered 2020-07-31T02:05:44Z
36 votes
SELECT 'test-a1' AS name1, 'test-a2' AS name2 
UNION ALL 
SELECT 'test-b1', 'test-b2'
UNION ALL 
SELECT 'test-c1', 'test-c2'
openshac answered 2020-07-31T02:05:59Z
22 votes

UNION ALL是最好的选择。 它比UNION快,并且您将拥有互斥的行。

HLGEM answered 2020-07-31T02:05:24Z
5 votes

扩展@openshac对于oracle的答案,因为以下提到的代码适用于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
Alok Chaudhary answered 2020-07-31T02:06:20Z
4 votes

您可以使用临时表,将其填入结果,然后从中选择

create table #tmpAAA (name1 varchar(10), name2 varchar(10))
insert into #tmpAAA (name1, name2) 
values ('test_a', 'test_b'),
       ('test_c', 'test_d'),
       ('test_e', 'test_f'),
       ('test_g', 'test_h'),
       ('test_i', 'test_j');
select * from #tmpAAA;

这将返回

name1   name2
==================
test_a  test_b
test_c  test_d
test_e  test_f
test_g  test_h
test_i  test_j
ajaali answered 2020-07-31T02:06:44Z
2 votes

我很想知道任何人都有更好的解决方案。 在过去,我曾使用过:

Select top 3 'Hardcode'
from tableWithLotsOfRows

您介意用123切换abc吗?

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

应该返回如下内容:

TestA1, Test-B1
TestA2, Test-B2
TestA3, Test-B3
TizzyFoe answered 2020-07-31T02:07:12Z
0 votes

在MySQL中,您可以使用工会

select * from 
    (select 2006 as year union
     select 2007 as year union
     select 2008
    ) as years
vencedor answered 2020-07-31T02:07:32Z
translate from https://stackoverflow.com:/questions/6345635/how-to-select-several-hardcoded-sql-rows