PostgreSql 外键

CREATE TABLE cities (
        city            varchar(20) primary key,
        location   varchar(20)
);
CREATE TABLE weather (
        city            varchar(20) references cities(city),
        wendu     int
);
CREATE TABLE cities (
city varchar(80) NOT NULL,
location varchar(80) NULL,
CONSTRAINT cities_pkey PRIMARY KEY (city)
);
在引用表中创建级联关系
CREATE TABLE weather (
city varchar(80) NULL,
wendu int4 NULL,
CONSTRAINT weather_city_fkey FOREIGN KEY (city) REFERENCES cities(city) ON DELETE CASCADE 
--CONSTRAINT weather_city_fkey FOREIGN KEY (city) REFERENCES cities(city) ON UPDATE CASCADE 
--CONSTRAINT weather_city_fkey FOREIGN KEY (city) REFERENCES cities(city) ON UPDATE SET NULL 
--CONSTRAINT weather_city_fkey FOREIGN KEY (city) REFERENCES cities(city) ON DELETE SET NULL 
--CONSTRAINT weather_city_fkey FOREIGN KEY (city) REFERENCES cities(city) ON DELETE CASCADE  ON UPDATE CASCADE 
--CONSTRAINT weather_city_fkey FOREIGN KEY (city) REFERENCES cities(city) ON UPDATE SET NULL ON DELETE CASCADE
);

1. 关联表的相关行同样被删除或修改;                               on delete cascade on update cascade
2. 删除被关联表的相关行,关联表中外键被设置为null;      on delete set null
3. 修改被关联表的关联键,关联表中外键被设置为null;      on update set null
4. 但是如果关联表的外键是null,那么就不满足两表的约束了,所以一般定义外键为not null。总之数据表中涉及到级联删除修改的操作,一般一定要慎重,业务上一定要按照级联关系控制操作,否则就可能误删数据。
5. 与foreign key相约束的,被关联表中的键必须是primary key or unique(查询时都是Index Scan),外键自身也要有索引。可以用查询计划查看。
关联表插入或更新时,要去被关联表中检查约束,所以被关联表中的键必须有索引,提高检查约束效率。
被关联表删除或更新时,会扫描关联表是否有相应的约束,所以关联表的外键最好有索引。

你可能感兴趣的:(Postgres)