oracle 添加 一 个 列 , 该 列 的 默认 值 设置 为 另 一 个 表 中 已 填充 的 列 的 出现 次数

wmvff8tz  于 2022-11-22  发布在  Oracle
关注(0)|答案(1)|浏览(120)

假设我有两个已经填充的表,我想向表Locations中添加一列nb_departments,该表使用位置中的部门数量进行初始化。

CREATE TABLE departments
(
    department_id   NUMBER(4) PRIMARY KEY,
    department_name VARCHAR2(30) NOT NULL,
    manager_id      NUMBER(6),
    location_id     NUMBER(4)    NOT NULL
);

CREATE TABLE locations
(
    location_id    NUMBER(4) PRIMARY KEY,
    street_address VARCHAR2(40),
    postal_code    VARCHAR2(12),
    city           VARCHAR2(30),
    state_province VARCHAR2(25),
    country_id     CHAR(2) NOT NULL
);

可以使用触发器或alter table add column default value来完成吗?

jgwigjjp

jgwigjjp1#

您可以建立检视:

CREATE VIEW vwlocations 
(
    location_id,
    street_address,
    postal_code,
    city ,
    state_province,
    country_id,
    nb_departments
) AS
SELECT  l.location_id,
        l.street_address,
        l.postal_code,
        l.city ,
        l.state_province,
        l.country_id,
        COUNT(d.location_id) AS nb_departments
FROM    locations l
        JOIN departments d
            ON l.location_id = d.location_id
GROUP BY l.location_id,
        l.street_address,
        l.postal_code,
        l.city ,
        l.state_province,
        l.country_id

如果确实要向现有表中添加列,则可以通过以下方式初始化列值,然后添加一个触发器来管理更新/插入/删除:

UPDATE locations SET locations.nb_departments = (SELECT COUNT(*) FROM departments WHERE locations.location_id = departments.location_id)

相关问题