SQLite:如何命名 "values" 子选择中的列

SQLite: how to name columns in a "values" subselect

在 postgres 中我可以说:

test=# select * from (values(1),(3),(7)) as foo(id);
 id
----
  1
  3
  7
(3 rows)

这意味着这样的子select随后可以使用foo.id等与其他表连接

在 sqlite 中我可以说:

sqlite> select * from (values(1),(3),(7)) as foo;

----------
1
3
7

但是如果我说 foo(id) 我会得到一个错误:

sqlite> select * from (values(1),(3),(7)) as foo (id);
Error: near "(": syntax error

显然,对于通常的 subselects(例如“(select ... as a, ... as b from... ) as foo”),您可以简单地命名每个字段.

我发现在这种情况下命名列的唯一简单解决方法是进行联合,例如:

sqlite> select * from (select 1 as id where 1=0 union values(1),(3),(7)) foo;
id        
----------
1         
3         
7         

SQLite 中这种 "subselects" 有没有更好的方法来命名列?

VALUES 创建的列具有您不想使用的名称(尽管有可能):

sqlite> .mode columns
sqlite> .header on
sqlite> select * from (values(1,2,3));
            :1          :2        
----------  ----------  ----------
1           2           3         
sqlite> select "", ":1", ":2" from (values(1,2,3));
            :1          :2        
----------  ----------  ----------
1           2           3         

这无法更改;没有比在 'real' SELECT 前加上 UNION ALL 更好的方法了。