如何使用值和空列在 postgresql 中创建临时 table

How to create temp table in postgresql with values and empty column

我是 postgresql 的新手。我想创建一个包含一些值和空列的临时 table。这是我的查询,但它没有执行,但在 ,(逗号)处给出错误。

CREATE TEMP TABLE temp1 
AS (
 SELECT distinct region_name, country_name 
 from opens 
 where track_id=42, count int)

我做错了什么?

如何创建临时 table,其中某些列的值使用 select 查询,而其他列为空?

您的错误来自您在 WHERE 子句附近的语句。

这应该有效:

CREATE TEMP TABLE temp1 AS 
(SELECT distinct region_name, 
        country_name,
        0 as count 
 FROM   opens 
 WHERE track_id=42)

只是 select 一个 NULL 值:

CREATE TEMP TABLE temp1 
AS
SELECT distinct region_name, country_name, null::integer as "count"
from opens 
where track_id=42;

强制转换为整数 (null::integer) 是必要的,否则 Postgres 将不知道用于附加列的数据类型。如果您想提供不同的值,您当然可以使用例如42 as "count" 而不是

注意count是保留关键字,所以要用双引号作为标识符。但是,最好找到一个不同的名称。

也没有必要将 CREATE TABLE AS SELECTSELECT 语句放在括号之间。

试试这个。

            CREATE TEMP TABLE temp1 AS 
            (SELECT distinct region_name, 
                    country_name,
                    cast( '0' as integer) as count
             FROM   opens 
             WHERE track_id=42);