ALTER TABLE 从表名 ADD CONSTRAINT 外键约束名 FOREIGN KEY (从表的外键) REFERENCES 主表名 (主表的主键); 1 注意:如果要给一个已存在的表添加 ON DELETE CASCADE 的外键约束,需要如下步骤: 删除已存在的外键约束。 添加一个 ON DELETE CASCADE 的外键约束。 删除外键约束 格式: alter table 从表名 drop ...
Summary: in this tutorial, you will learn about the PostgreSQL foreign key and how to add foreign keys to tables using foreign key constraints. Introduction to PostgreSQL Foreign Key Constraint In PostgreSQL, a foreign key is a column or a group of columns in a table that uniquely identifies ...
CREATE TABLE orders ( order_id integer PRIMARY KEY, product_no integer, quantity integer ); 给订单表增加外键: alter table orders add constraint orders_product_no_fkey foreign key ("product_no") references products("product_no"); 删除外键约束 如果要删除外键约束,则可以执行以下命令: alter table...
CREATE TABLE table1 ( id SERIAL PRIMARY KEY, column1 VARCHAR(50), column2 INTEGER, FOREIGN KEY (column2) REFERENCES table2(id) ); ``` 2、如果表已经创建,可以使用ALTER TABLE语句添加外键约束,如下所示: ```sql ALTER TABLE table1 ADD CONSTRAINT fk_column2 FOREIGN KEY (column2) REFERENCES t...
"t1_pkey"PRIMARYKEY, btree (a) Referencedby: TABLE"t2"CONSTRAINT"t2_b_fkey"FOREIGNKEY(b)REFERENCESt1(a) postgres=# \d t2 Table"public.t2" Column| Type | Collation | Nullable |Default ---+---+---+---+--- a |integer| |notnull| b |integer| | | c |...
createtabletbl_foreign_refd( aintnotnull, bintnotnull, cvarchar);altertabletbl_foreign_refdaddconstraintpk_tbl_foreign_refd_a_bprimarykey(a,b);createtabletbl_foreign( aint, bint, cvarchar);altertabletbl_foreignaddconstraintfk_tbl_foreign_a_bforeignkey(a,b)referencestbl_foreign_refd(a,b)...
ADD CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id); ``` 3、删除外键约束:如果需要删除外键约束,可以使用 ALTER TABLE 命令来删除。 例如,删除 orders 表格中 customer_id 列上的外键约束: ```sql ALTER TABLE orders DROP CONSTRAINT fk_customer; ``` 总的来说,在 PostgreSQL ...
addconstraint字段名 unique(字段名) --外键约束: altertable表名 addconstraint字段名--"FK"为外键的缩写 foreignkey (字段名)references关联的表名(关联的字段名)--注意'关联的表名'和'关联的字段名' altertable表A add constraint FK_B foreign key (ticket_no)references表B(ticket_no) ...
add constraint 外键名 foreign key (从表字段列表) references 主表名 (主表字段列表) [on delete cascade|set null]; 1. 2. 3. 4. 说明: 外键名,Oracle的标识符,建议采用FK_从表名_主表名的方式命名。 主表执行删除行时,其主键值在从表里存在便阻止删除,如果on delete cascade,连带从表的相关行一起...
(100)); alter table test_1 add constraint test_1_uq unique (id,name); --要提供外键,必须先建立唯一约束 create table test_2(id numeric,a_id numeric,a_name character varying (100)); alter table test_2 add constraint test_fk foreign key (a_name,a_id) references test_1(name,id); ...