首页 > 解决方案 > SQL 添加一个新列,其值只能在几个固定选项中

问题描述

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

CREATE TABLE brands (
    Brand varchar(255),
    Contact varchar(150),
    Address varchar(255),
    Location varchar(50),
)

我希望添加一个名为 country 的新列,其值只能从以下值中选择:“Japan”、“New Zealand”、“US”、“France” 在此处输入图像描述

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

标签: sqlsql-server

解决方案


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

检查约束:

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

但我们实际上可以做得更好!国家已经有一个明确定义的“事物”来唯一标识它们: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);

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


推荐阅读