sql - SQL 添加一个新列,其值只能在几个固定选项中
问题描述
我想在我的数据表中添加一个带有 SQL 的新列,如下所示,
CREATE TABLE brands (
Brand varchar(255),
Contact varchar(150),
Address varchar(255),
Location varchar(50),
)
我希望添加一个名为 country 的新列,其值只能从以下值中选择:“Japan”、“New Zealand”、“US”、“France”
我可以添加新列,但我不知道如何为该列设置有限的可选值。如果您有想法,请提供帮助。非常感谢
解决方案
您可以使用检查约束或外键。
检查约束:
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
将表连接到表。countries
country_code
推荐阅读
- r - R:在集群上运行 R 时出现内存限制错误
- swagger - Swagger UI - 请求未经授权然后隐藏试用按钮
- c++ - MFC。查询 CInternetSession 类中的 GetFtpConnection 方法
- netty - 带有 setReuseAddress(true) 的 gRPC Java 服务器?
- php - 单击发送按钮时,页面未显示文本已成功发送
- c# - ASP.NET Core 模型按国外字段排序
- java - Controller.Controller 中的错误字段存储库需要找不到类型为“Controller.Repository”的 bean
- c++ - 带有 CMake 的 OpenSSL - 未知选项:构建 openSSL 时的 --sysroot
- ios - 文件“ProjectTests.swift”是模块“Project”的一部分;忽略导入
- javascript - Laravel,如何使用 Google Map Marker 从 javascript 函数调用路由