您可以使用检查约束或外键。
检查约束:
alter table brands add country_name varchar(64) not null;
alter table brands add constraint ck_country_list
check (country_name in ('Japan', 'New Zealand', 'US', 'France'));
对于检查约束,允许的值永远不会改变(除非您更改约束代码)。使用外键,允许的值存储在另一个表中。只要该值存在于另一个表中,它们就允许存在于该表中。
create table countries(country_name varchar(64) not null primary key);
insert countries (country_name)
values ('France'), ('New Zealand') -- etc
alter table brands add country_name varchar(64) not null;
alter table brands add constraint fk_brands_countries
foreign key (country_name) references countries (country_name);
但我们实际上可以做得更好!国家已经有一个明确定义的“事物”来唯一地标识它们:ISO 3166 国家/地区代码 https://www.iso.org/iso-3166-country-codes.html。您可以使用 2 字符、3 字符或 int 版本。对于主键来说,尽可能使用定义明确的标准始终是一个好主意。
这是超出您当前正在尝试学习的内容的下一个级别。但它可能是这样的:
create table countries
(
country_code char(2) not null primary key clustered,
country_name varchar(64) not null
);
insert countries (country_code, country_name)
values ('FR', 'France'), ('NZ', 'New Zealand') -- etc etc;
alter table brands add country_code char(2) not null;
alter table brands add constraint fk_brands_countries
foreign key (country_code) references countries (country_code);
当你想获得国家名称时,你加入brands
表到countries
表使用country_code
column.