0

我是数据库设计的新手,并且在 Postgres 中创建了我的表。但是,我需要将我的一张表的数据类型从更改dateinteger'. 但是,当我添加代码来执行此操作时,我收到以下错误:

ERROR:  cannot cast type date to integer
LINE 13: ALTER COLUMN year TYPE INT USING year::integer;

建议我添加该USING行来覆盖此错误,但它并没有解决我的问题。

以下是整个代码,任何建议将不胜感激。

BEGIN;


CREATE TABLE IF NOT EXISTS public."Actor"
(
    actor1_name "char",
    actor_id numeric,
    actor_type "char",
    PRIMARY KEY (actor_id)
);

CREATE TABLE IF NOT EXISTS public."Country"
(
    country_name "char",
    country_id numeric,
    PRIMARY KEY (country_id)
);

CREATE TABLE IF NOT EXISTS public."Event"
(
    event_id numeric,
    event_type_descr "char",
    event_date date,
    **year date,**
    fatalities numeric,
    event_type "char",
    PRIMARY KEY (event_id)
);

**ALTER TABLE "Event" 
ALTER COLUMN year TYPE INT USING year::integer;**
    
CREATE TABLE IF NOT EXISTS public."Location"
(
    location_name "char",
    longitude numeric,
    latitude numeric,
    location_id numeric,
    PRIMARY KEY (location_id)
);

CREATE TABLE IF NOT EXISTS public."Region"
(
    region_name "char",
    region_id numeric,
    PRIMARY KEY (region_id)
);

CREATE TABLE IF NOT EXISTS public."Event_Actor"
(
    "Event_event_id" numeric,
    "Actor_actor_id" numeric
);

ALTER TABLE public."Location"
    ADD FOREIGN KEY (location_id)
    REFERENCES public."Country" (country_id)
    NOT VALID;


ALTER TABLE public."Country"
    ADD FOREIGN KEY (country_id)
    REFERENCES public."Region" (region_id)
    NOT VALID;


ALTER TABLE public."Event_Actor"
    ADD FOREIGN KEY ("Event_event_id")
    REFERENCES public."Event" (event_id)
    NOT VALID;


ALTER TABLE public."Event_Actor"
    ADD FOREIGN KEY ("Actor_actor_id")
    REFERENCES public."Actor" (actor_id)
    NOT VALID;


ALTER TABLE public."Event"
    ADD FOREIGN KEY (event_id)
    REFERENCES public."Location" (location_id)
    NOT VALID;

END;
4

1 回答 1

0

从列名中假设您希望日期的年份部分为整数(您应该在问题中清楚地表达这一点!),您可以使用extract().

ALTER TABLE "Event"
            ALTER COLUMN year
                         TYPE integer
                              USING extract(YEAR FROM year);

附带说明:避免区分大小写的对象名称,例如"Event". 他们只会让事情变得更难,但没有任何好处。如果您需要“漂亮”的标签,那是表示层的工作,而不是数据库。

于 2021-11-07T18:45:52.467 回答