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也进行了递增。
为什么要这样设计?