SQL添加一个新列,其值只能在几个固定选项中

Xav*_*orL 0 sql sql-server

我想在我的数据表中添加一个带有 SQL 的新列,如下所示,

CREATE TABLE brands (
    Brand varchar(255),
    Contact varchar(150),
    Address varchar(255),
    Location varchar(50),
)
Run Code Online (Sandbox Code Playgroud)

我想添加一个名为 country 的新列,该值只能从以下值中选择:“日本”、“新西兰”、“美国”、“法国” 在此处输入图片说明

我可以添加新列,但我不知道如何为该列设置有限的可选值。如果您有想法,请帮助。非常感谢

all*_*ran 5

您可以使用检查约束或外键。

检查约束:

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'));
Run Code Online (Sandbox Code Playgroud)

使用检查约束,允许的值永远不会改变(除非您更改约束代码)。使用外键,允许的值存储在另一个表中。只要该值存在于另一个表中,它们就被允许出现在该表中。

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);

Run Code Online (Sandbox Code Playgroud)

但我们实际上可以做得更好!国家已经有一个明确定义的“事物”来唯一标识它们:ISO3166 国家代码。您可以使用 2 char、3 char 或 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);
Run Code Online (Sandbox Code Playgroud)

当您想要获取国家/地区名称时,您brands可以countries使用country_code列将表连接到表中。