📜  PostgreSQL – 删除列

📅  最后修改于: 2022-05-13 01:57:15.618000             🧑  作者: Mango

PostgreSQL – 删除列

PostgreSQL 还支持 ALTER TABLE 语句中的 DROP COLUMN 子句来删除表的一列或多列。当您从表中删除一列时,PostgreSQL 将自动删除所有涉及该列的索引和约束。

Syntax:
ALTER TABLE table_name 
DROP COLUMN column_name;

现在让我们看一个例子。

例子:
首先,我们创建了几个表(例如, bookscategoriespublishers )用于演示,具有以下描述的关系:


我们使用以下语句创建上述表格:

CREATE TABLE publishers (
    publisher_id serial PRIMARY KEY,
    name VARCHAR NOT NULL
);

CREATE TABLE categories (
    category_id serial PRIMARY KEY,
    name VARCHAR NOT NULL
);

CREATE TABLE books (
    book_id serial PRIMARY KEY,
    title VARCHAR NOT NULL,
    isbn VARCHAR NOT NULL,
    published_date DATE NOT NULL,
    description VARCHAR,
    category_id INT NOT NULL,
    publisher_id INT NOT NULL,
    FOREIGN KEY (publisher_id) REFERENCES publishers (publisher_id),
    FOREIGN KEY (category_id) REFERENCES categories (category_id)
);

此外,我们基于bookspublishers表创建了一个视图,如下所示:



CREATE VIEW book_info AS SELECT
    book_id,
    title,
    isbn,
    published_date,
    name
FROM
    books b
INNER JOIN publishers P ON P .publisher_id = b.publisher_id
ORDER BY
    title;

如果我们想删除books category_id列,我们使用以下语句:

ALTER TABLE books DROP COLUMN category_id;

现在我们使用以下语句检查 books 表:

SELECT * FROM books;

输出: