Q1:
新建table venues:
create table venues (
venue_id serial primary key,
name varchar(255),
street_address text,
type char(7) check (type in ('public','private')) default 'public',
postal_code varchar(9),
country_code char(2),
foreign key (country_code,postal_code) references cities(country_code,postal_code) match full
);table cities 中已有记录:
select * from cities;
name | postal_code | country_code
----------+-------------+--------------
portland | 87200 | us
shenzhen | 518120 | cn
postal_code 和country_code为复合主键。
往venues中插入不合法记录:
insert into venues(name,postal_code,country_code) values('crystal ballroom','97205','us');
ERROR: insert or update on table "venues" violates foreign key constraint "venues_country_code_fkey"
DETAIL: Key (country_code, postal_code)=(us, 97205) is not present in table "cities".再接着插入合法记录:
insert into venues(name,postal_code,country_code) values('crystal ballroom','87200','us');
INSERT 0 1
查询venues的记录:
select * from venues;
venue_id | name | street_address | type | postal_code | country_code
----------+------------------+----------------+---------+-------------+--------------
2 | crystal ballroom | | public | 87200 | us
(1 row)发现venue_id属性为2,得知插入不合法记录的时候venue_id也进行了递增。
为什么要这样设计?
本文通过具体示例探讨了SQL中外键约束的工作原理及其如何确保数据一致性。文章演示了当尝试插入违反外键约束的数据时数据库的行为,并展示了合法数据插入后的效果。
1500

被折叠的 条评论
为什么被折叠?



