向 SQL 中的视图添加新列

Add a new column to a view in SQL

我有一个数据库,我已经用我想要的数据创建了一个视图。数据看起来像这样:

    n     |   value |
----------+---------+
 50404791 |     112 | 
  5034591 |     164 |
 50280287 |      31 |

我想添加这样一列文字:

    n     |   value | status |
----------+---------+--------+
 50404791 |     112 |default | 
  5034591 |     164 |biggest |
 50280287 |      31 |smallest|

我试过 Alter Table Table1 Add Column status text ; 但文本似乎不是数据类型。有什么建议吗?

您需要删除并重新创建视图 - 您不能更改现有视图。是的,文本是一种数据类型。

在 Rextester.com 上测试(记住,无论如何要避免在视图中使用 SELECT *

CREATE TABLE TABLE1 (ID INTEGER);
CREATE VIEW V1 AS SELECT * FROM TABLE1;
INSERT INTO TABLE1 VALUES (0);

ALTER TABLE TABLE1 ADD COLUMN STATUS TEXT;    
INSERT INTO TABLE1 (ID, STATUS) VALUES (1, 'aaa');

SELECT * FROM V1;
DROP VIEW V1;

CREATE VIEW V1 AS SELECT * FROM TABLE1;
SELECT * FROM V1;

输出:

    id
1   0
2   1

    id  status
1   0   NULL
2   1   aaa

我在 postgresql.org

上找到了答案

You can do from pgAdmin by right-clicking on the view and select CREATE SCRIPT uncomment: DROP VIEW ; and edit the CREATE VIEW to drop the column.

However if the view is used in other views you have to drop them all and recreate in sequence.

Alternatively you can delete the columns from the pg_catalog.pg_attribute table. Make sure however that you know you deleting only the one's you want to delete and not other tables columns... using the below:

delete from pg_attribute where attrelid = regclass 'yourviewname' and attname = 'columnnametodrop'

Best to first do couple of selects until you have the selection correct:

select attrelid::regclass as whatever, * from pg_attribute where attname = 'columnnametodrop'

Johan Nel.

在 Postgres 中,您可以在不删除视图的情况下使用 CREATE OR REPLACE 并执行以下操作

    CREATE OR REPLACE VIEW View1 AS
        SELECT value, status FROM Table 1;

更改原始 table 只会更改 table 而不会更改视图。