导入
添加新列
学习如何向现有表中添加一列。
到目前为止,我们已经熟悉了多种查询操作,如 insert、delete、update 和 select。我们也使用了多种运算符来满足不同的需求。现在,我们将学习如何向现有表中添加一列。假设我们想要引入一个名为 identity 的列。我们假设每位客户都有一个唯一的身份编号,因此希望在数据模型中引入这一概念。
alter 表命令
我们执行以下 alter table 命令来添加该列:
1alter table customers add column(identity varchar(32) not null);
在实际执行该命令之前,让我们先分析一下命令中各部分的含义。
alter table 命令的组成部分
- 我们使用
alter table命令向现有表中添加新列。通常,alter table可用于执行多种表结构的修改。其中一种就是添加列。稍后我们会看到其他用法。 - 指定我们要修改的表的名称。
- 使用
add column关键字,因为我们希望添加一列。 - 添加新列时,需要指定该列的属性,这些属性写在括号内。其格式与创建表时定义列的方式类似:
- 首先,指定新列的名称。
- 然后,指定列的数据类型。这里使用
varchar类型,并设置长度为 32,表示该列最多可存储 32 个字符的字符串。 - 使用
not null表示该列必须始终有值,不允许为空。没有identity的客户将无法被接受。
让我们通过执行该命令并检查表是否发生变化来验证其效果:
1alter table customers add column(identity varchar(32) not null); 2select * from customers; /* 验证查询结果 */
由于 customers 表中已存在一些记录,因此两位客户的 identity 值目前都为空字符串 ""。接下来,我们更新已有客户的 identity 值:
1update customers set identity = 'JW0001' where id = 1; 2update customers set identity = 'ML0001' where id = 3; 3select * from customers /* 查看更改后的结果 */
我们使用两条 update 语句:第一条更新 id = 1 的客户身份信息,第二条更新 id = 3 的客户身份信息。
两个 identity 字段均已成功更新。现在我们可以根据 identity 查询客户了。例如:
1select * from customers where identity = 'JW0001';
如果只记得某个客户的 identity 以 JW 开头,该如何查找?我们可以使用 like 运算符:
1select * from customers where identity like 'JW%';