学习目标
学习表的约束、表的默认值、自增类型等技术。
常见的表的约束:
1. 主键约束
“PRIMARY KEY” 主键约束,用于标识唯一对应的记录
2. 外键约束
“FOREIGN KEY” 外键约束
3. 非空约束
“NOT NULL” 非空约束
4. 唯一性约束
“UNIQUE” 唯一性约束
5. 默认值约束
“DEFAULT” 默认值约束,用于设置字段默认值
6. 自增约束
“AUTO_INCREMENT” 自增约束
课程作业
1.创建表的时候定义列级约束
列级约束主要指:primary key, not null约束.
drop table if exists col_constraint;
create table col_constraint ( id int primary key, name char(20) not nulll);
insert into col_constraint (id, name) values(1, '赵四');
insert into col_constraint (id, name) values(2, '张三');
-- 失败
-- insert into col_constraint (id, name) values(2, '张三');
-- insert into col_constraint (id, name) values(4, );
2.创建表的时候定义表级约束
drop table if exists test001;
create table test001(
id bigint,
name varchar(50) not null, -- 创建列级not null约束
age int,
primary key(id) -- 创建表级约束
);
insert into test001 values(1,'user1',50);
select * from test001;
\d test001
3.为表的属性定义默认值
可以在创建表时,为某一列或者多列设置默认值
--执行下面的语句,在创建表的时候为表的某个列定义默认值:
drop table if exists test002;
create table test002(
id bigint,
name varchar(28) not null,
age int default 20, -- 为该列定义默认值为20
primary key(id)
);
--下面的SQL insert语句,在向表test插入数据时,没有提供age列的值:
insert into test002(id,name) values(1,'user1');
insert into test002(id,name) values(2,'user2');
select * from test002;
4.如果在创建表的时候,没有为某列定义默认值,缺省的默认值是空值null
drop table if exists test002;
sel
create table test002(
id bigint,
name varchar(28) not null,
age int default 20, -- 为该列定义默认值为20
primary key(id)
);
--下面的SQL insert语句,在向表test插入数据时,没有提供age列的值:
insert into test002(id,name) values(1,'user1');
insert into test002(id,name) values(2,'user2');
select * from test002;
可以看到查询结果年龄为20,默认值。
5.创建表时使用自增数据类型
-创建一个带有serial数据类型的测试表invoice:
drop table if exists invoice;
create table invoice(invoicenum serial NOT NULL,name varchar(20));
--为表invoice插入3条记录,并查看插入数据后的表的数据:
insert into invoice(name) values('user1');
insert into invoice(name) values('user2');
insert into invoice(name) values('user3');
--可以看到每插入一条记录到表invoice后,列invoicenum的值会自增1。
select * from invoice;
6.使用现有的表创建新表
--执行下面的SQL语句,将创建新表,并且会将旧表的数据拷贝给新表:
DROP TABLE if exists ta;
CREATE TABLE ta AS SELECT * FROM invoice;
SELECT * FROM ta;
--执行下面的SQL语句,创建和旧表的表结构相同的新表,但是不会将旧表的数据拷贝给新表:
DROP TABLE if exists tb;
CREATE TABLE tb AS SELECT * FROM invoice WHERE 1=2;
SELECT * FROM tb;
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




