postgresql 错误:在“FOREIGN”或其附近有语法错误(SQLSTATE 42601)

fdbelqdn  于 2022-11-04  发布在  PostgreSQL
关注(0)|答案(1)|浏览(310)

我尝试向订单表中已经存在的列添加约束,即它是foring键:

ALTER TABLE IF EXISTS public.orders DROP COLUMN IF EXISTS location_id;

ALTER TABLE IF EXISTS public.orders
    ADD COLUMN location_id bigint
    CONSTRAINT orders_location_id_fkey FOREIGN KEY (location_id)
        REFERENCES public.locations (id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
aiqt4smr

aiqt4smr1#

不能在列定义中使用“表约束条件”语法。请使用“列约束条件”语法:

... ADD COLUMN location_id bigint
        CONSTRAINT orders_location_id_fkey REFERENCES public.locations (id)

请参见the documentation中的语法图:
***column_constraint***
[...]
***column_constraint***是:
[ CONSTRAINT***constraint_name***]
[...]
REFERENCES***reftable***[ (***refcolumn***) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ]
[ ON DELETE***referential_action***] [ ON UPDATE***referential_action***] }

相关问题