psql-06表:约束
默认值
可以理解为建表时没定义的默认值为
null,表示未知,//注意和js中null不一样;建表时设置
create table child(id int, age int default 18);
- 更新时使用
update child set age = default where id = 1;
- 默认值可以是个表达式,它会在插入时计算
create table test (id int, created_time timestamp default now());
约束
检查约束
check给某些字段值指定一个范围:
create table child (name text, age int constraint ck_age check (age < 18 and age > 7) );
create table NotChild (name text, age int constraint ck_age check (age >18 or age < 7) );
//也可以都放到最后
create table books (book_no int, name text, price numeric, discounted_price numeric,
check(price > 0), check(discounted_price > 0), check(price > discounted_price) );
create table books (book_no int, name text, price numeric, discounted_price numeric,
check(price > 0 and discounted_price > 0 and price > discounted_price) );
非空约束
- 确保一个字段值不为空
create table books (book_no int not null, name text);
//相当于
create table books (book_no int, name text, check(book_no is not null));
主键
- 如果表的主键只是一个字段组成,则可以通过直接在后面加
primary key来指定主键; - 如果由多个字段组成,成为组合主键;
create table test (id1 int, id2 int, note varchar(20), constraint key_test primary key(id1, id2) );
唯一约束
- 也可以指定唯一键;
- 主键一定是唯一键,反之不是;
- 主键不能为空,唯一键可以;
create table test (id1 int, id2 int, id3 int, note varchar(20), constraint key_test primary key(id1, id2) , constraint uk_test unique(id3) );
外键约束
- 用于约束本表中的一个字段或多个字段的数值必须出现在另一个表的资格或多个字段中
//注意:这里要确保class_no unique
create table class(
class_no int primary key,
class_name varchar(40)
);
create table student(
student_no int primary key,
student_name varchar(40),
age int,
class_no int references class(class_no)
);
//建立外键之后,student中就不能插入class中不存在的class_no值
用其他表作为模版创建
create table baby (like child);
//注意这样创建并没有把源表的约束复制过来,需要添加
including defaults
including constraints
including indexs
including storage
including comments
including all
create table baby2 (like child including all);
临时表
- 创建的临时表会在一个特殊的模式中:
pg_temp_XX; - 无论是那种临时表,会话结束后就会消失;
- 会话级的临时表, 数据只保存在当前会话周期中;
- 在另一个
session中无法访问
create temporary table tmp (id int primary key, note text); //temporary可以缩写为temp
- 事务级临时表,数据只保存在当前事务中;
create temporary table tmp (id int primary key, note text) on commit delete rows;
begin; //事务开始
insert into values(1, 'a'); //注意在事务外是无法插入数据的
insert into values(2, 'b');
select * from tmp;
end; //事务结束,tmp表还存在。但数据已经消失;
修改表
- 对已经建立的表使用
alter table来修改表结构
增加字段
alter table class add column class_teacher varchar(40);
//设置默认值会对已经存在的行会自动填充;
删除字段
- 和这个字段相关的约束也会被删除;
alter table class drop column class_no;
- 如果存在外键依赖不能直接删除,必须要指明删除任何依赖在该字段的东西;
alter table class drop column class_no cascade;
增加约束
- 给表增加约束前要确定该表符合约束条件,否则会失败;
alter table student alter column student_name set not null; //非空约束
alter table student add check(age < 16); //检查约束
alter table class add constraint unique_class_teacher unique(class_teacher); //唯一约束
删除约束
alter table student drop constraint student_age_check;
//非空约束是没有名称的
alter table student alter column student_name drop not null;
修改默认值
- 不会影响已保存的行数据
alter table student alter column age set default 15;
删除默认值
- 不会影响已保存的行数据
alter table student alter column age drop default;
修改字段数据类型
- 只有每一行的该项数据都能隐式地替换成新的类型,转行才能成功;
alter table student alter column student_name type text;
- 注意
PostgesSQL会试图把字段的约束/默认值做相应转换,但不一定会成功;所有最好成功改变类型后再手动添加一遍;
重命名字段
alter table book rename column book_no to book_id;
重命名表
alter table class rename to classes;
增加约束时的判断方法
- 对表增加约束,如果约束已经存在则跳过;
CREATE OR REPLACE FUNCTION create_constraint_if_not_exists (t_name text, c_name text, constraint_sql text)
RETURNS void
AS
$$
begin
if not exists (select constraint_name
from information_schema.constraint_column_usage
where table_name = t_name and constraint_name = c_name) then
execute 'ALTER TABLE ' || t_name || ' ADD CONSTRAINT ' || c_name || ' ' || constraint_sql;
end if;
end;
$$
LANGUAGE plpgsql VOLATILE;
//excute
SELECT create_constraint_if_not_exists ('user_sessions', 'session_pkey', 'PRIMARY KEY ("sid") NOT DEFERRABLE INITIALLY IMMEDIATE');
psql-06表:约束的更多相关文章
- 常用sql语句总结(二)(更新数据,序列,创建数据表,约束,注释)
常用sql语句总结(二)(更新数据,序列,创建数据表,约束,注释) 一. 增 INSERT INTO 数据表(字段,字段,-) VALUES(值,值-); INSERT INTO emp(empno, ...
- Sql中常用的创建表 约束 主外键 增删改查的语句
创建数据库 USE master; GO --日记数据库 create database DiaryBase on ( name=DiaryBase_Dat,--逻辑名称 FILENAME='c:\D ...
- oracle习题练习-表空间-用户-表-约束
题一 1. 创建名字为hy_tablespace的表空间,默认大小为10M;@@ 2. 创建一个用户,用户名以自己名字命名,并指定命名空间为hy_tablespace;@@@@ ...
- SQL Tuning 基础概述06 - 表的关联方式:Nested Loops Join,Merge Sort Join & Hash Join
nested loops join(嵌套循环) 驱动表返回几条结果集,被驱动表访问多少次,有驱动顺序,无须排序,无任何限制. 驱动表限制条件有索引,被驱动表连接条件有索引. hints:use_n ...
- css整理-06 表和列表
表格式化 表布局 table, display:table caption, display: table-caption thead, display: table-header-group tbo ...
- 22----2013.06.29---HTML--html介绍.超链接和图片,表格,表单,表单标签,meta,复习当天内容
01 HTML HTML :Hypertext Markup Language 超文本标记语言(类似于 裸奔的人.) 作用:向用户展示信息. CSS: Cascading 层叠样式表(类似于 人的 ...
- MySQL数据库基础(二)(约束以及修改数据表)
一,约束以及修改数据表 约束的作用?1.约束保证数据的完整性.一致性:2.约束分为表级约束.列级约束:3.约束类型包括:NOT NULL(非空约束).PRIMARY KEY(主键约束).UNIQUE ...
- MySQL基础(二)(约束以及修改数据表)
一,约束以及修改数据表 约束的作用?1.约束保证数据的完整性.一致性:2.约束分为表级约束.列级约束:3.约束类型包括:NOT NULL(非空约束).PRIMARY KEY(主键约束).UNIQUE ...
- MySQL数据库3分组与单表、多表查询
目录 一.表操作的补充 1.1null 和 not null 1.2使用not null的时候 二.单表的操作(import) 2.1分组 2.1.1聚合函数 2.1.2group by 2.1.3h ...
随机推荐
- 掌握VS2010调试 -- 入门指南
1 导言 在软件开发周期中,测试和修正缺陷(defect,defect与bug的区别:Bug是缺陷的一种表现形式,而一个缺陷是可以引起多种Bug的)的时间远多于写代码的时间.通常,debug是指发现缺 ...
- iOS开发MAC下配置svn
版本控制对于团队合作显得尤为重要,那么如何在iOS开发中进行版本控制呢?在今天的博客中将会介绍如何在MAC下配置SVN服务器,如何导入我们的工程,如何在Xcode中进行工程的checkOut和Comm ...
- asp.net 图片下载
string fileName = "123.jpg";//图片名字 string filePath = Server.MapPath(&qu ...
- 让UserControl能显示焦点状态
'set the control can display the focus status Protected Overrides Sub OnGotFocus(ByVal e As System.E ...
- xmpp SASL 定义
SASL 定义 <摘抄自:xmpp_3920> [SASL]的 profiling 需求要求协议定义 供以下信息: 服务名:“xmpp” 初始序列:初始实体 供一个开放 XML 流头后,并 ...
- [Android Pro] Android性能优化典范第一季
reference to : http://www.cnblogs.com/hanyonglu/p/4244035.html#undefined 2015年伊始,Google发布了关于Android性 ...
- October 10th 2016 Week 42nd Monday
What makes life dreary is the want of motive. 没有了目标,生活便黯然无光. Motive and goal, are absolutely indispe ...
- August 19th 2016 Week 34th Friday
Friends are not the people you meet at the top, they are the people who were with you at the bottom. ...
- 3ds max的动画输出
转自:http://zhidao.baidu.com/link?url=qc3vV2A9-ydb-YiVKoF7z_bIIRlmLSkyl8DcuWNYn8FaBxa2BDVLwuGPX_jYWxbw ...
- 假期(codevs 3622)
题目描述 Description 经过几个月辛勤的工作,FJ决定让奶牛放假.假期可以在1-N天内任意选择一段(需要连续),每一天都有一个享受指数W.但是奶牛的要求非常苛刻,假期不能短于P天,否则奶牛不 ...