SELECT *除了第n列

问题描述 投票:8回答:3

是否有可能SELECT *但没有n-th列,例如2nd

我有一些视图有4列和5列(每个列都有不同的列名,第二列除外),但我不想显示第二列。

SELECT * -- how to prevent 2nd column to be selected?
FROM view4
WHERE col2 = 'foo';

SELECT * -- how to prevent 2nd column to be selected?
FROM view5
WHERE col2 = 'foo';

无需列出所有列(因为它们都具有不同的列名)。

postgresql postgresql-9.4
3个回答
11
投票

真正的答案是你实际上不能(参见LINK)。这是几十年来一直被要求的功能,开发人员拒绝实现它。最佳做法是提及列名而不是*。然而,使用*本身就是性能惩罚的来源。

但是,如果您确实需要使用它,则可能需要直接从架构中选择列 - >检查LINK。或者如以下示例使用两个PostgreSQL内置函数:ARRAY和ARRAY_TO_STRING。第一个将查询结果转换为数组,第二个将数组组件连接成一个字符串。可以使用ARRAY_TO_STRING函数的第二个参数指定列表组件分隔符;

SELECT 'SELECT ' ||
ARRAY_TO_STRING(ARRAY(SELECT COLUMN_NAME::VARCHAR(50)
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME='view4' AND
            COLUMN_NAME NOT IN ('col2')
    ORDER BY ORDINAL_POSITION
), ', ') || ' FROM view4';

其中字符串与标准运算符||连接。 COLUMN_NAME数据类型是information_schema.sql_identifier。此数据类型需要显式转换为CHAR / VARCHAR数据类型。

但是也不推荐这样做,如果从长远来看添加更多列,但该查询不一定需要它们,该怎么办?你会开始拉出比你需要的更多的列。

如果select是插入的一部分,如果如此

Insert into tableA (col1, col2, col3.. coln) Select everything but 2 columns FROM tableB

列匹配错误,插入失败。

这是可能的,但我仍然建议为每个选择写入所需的列,即使几乎每列都是必需的。

结论:

由于您已经在使用VIEW,最简单和最可靠的方法是改变您的视图并提及列名,不包括您的第二列。


0
投票

对于列col1,col2,col3和col4,您需要请求

SELECT col1, col3, col4 FROM...

省略第二列。请求

SELECT * 

会得到你所有的专栏


0
投票
-- my table with 2 rows and 4 columns 
DROP TABLE IF EXISTS t_target_table;
CREATE TEMP TABLE t_target_table as 
SELECT 1 as id, 1 as v1 ,2 as v2,3 as v3,4 as v4
UNION ALL 
SELECT 2 as id, 5 as v1 ,-6 as v2,7 as v3,8 as v4
;

-- my computation and stuff that i have to messure, any logic could be done here !
DROP TABLE IF EXISTS t_processing;
CREATE TEMP TABLE t_processing as 
SELECT *, md5(t_target_table::text) as row_hash, case when v2 < 0 THEN true else false end as has_negative_value_in_v2
FROM t_target_table
;

-- now we want to insert that stuff into the t_target_table 

-- this is standard
-- INSERT INTO t_target_table (id, v1, v2, v3, v4) SELECT id, v1, v2, v3, v4 FROM t_processing;

-- this is andvanced ;-) 

INSERT INTO t_target_table 
-- the following row select only the columns that are pressent in the target table, and ignore the others.
SELECT r.* FROM (SELECT to_jsonb(t_processing) as d FROM t_processing) t JOIN LATERAL jsonb_populate_record(NULL::t_target_table, d) as r ON TRUE
;
-- WARNING : you need a object that represent the target structure, an exclusion of a single column is not possible
© www.soinside.com 2019 - 2024. All rights reserved.