【数据库】PostgreSQL数据库入门(二)
1. 模式
模式在PostgreSQL中,类似于目录。同一数据库,不同模式下,可以存放相同名称的数据表。模式下,通常可以存放不同的数据对象,如表、视图、函数、存储过程、触发器、索引等。默认情况下会使用系统创建的public作为数据表的schema。
postgres=# dn List of schemas Name | Owner --------+---------- public | postgres (1 row)
通常我们可以使用create关键字直接创建模式,通过[schema_name].table_name来指定需要将数据表创建在哪个模式下。
create schema myschema; create table myschema.tb_user ( id serial primary key);
模式在删除时使用drop关键字,需要确保模式中不存在任何数据库对象,否则需要使用cascade进行级联删除。
2. Exclusion约束
PostgreSQL也提供了许多约束,如主键、唯一、不为空等等。Exclusion是一种排他约束。
- 要获得扩展支持,首先我们需要安装PostgreSQL的另一组件,需要根据PostgreSQL的版本进行选择。执行yum -y install postgresql12-contrib.x86_64即可。
- 为数据库创建扩展。
postgres=# create extension btree_gist; CREATE EXTENSION
- 创建exclusion约束。
postgres=# create table public.tb_employee ( postgres(# id serial primary key, postgres(# name text, postgres(# age integer, postgres(# exclude using gist (name with =, age with <>) postgres(# ); CREATE TABLE
- name相同,age不相同则不允许插入
postgres=# insert into tb_employee(name, age) values(Zhangsan, 12); INSERT 0 1 postgres=# insert into tb_employee(name, age) values(Zhangsan, 13); ERROR: conflicting key value violates exclusion constraint "tb_employee_name_age_excl" DETAIL: Key (name, age)=(Zhangsan, 13) conflicts with existing key (name, age)=(Zhangsan, 12). postgres=# insert into tb_employee(name, age) values(Lisi, 12); INSERT 0 1
3.存储过程(procedure)
PostgreSQL官方支持PL/pgSQL、PL/Tcl、PL/Perl和PL/Python等过程语言,同时还支持第三方提供的过程语言,如PL/Java、PL/PHP、PL/Py、PL/R、PL/Ruby、PL/Scheme、PL/sh。
4. Json和Jsonb数据类型用法
- 创建数据表
- 插入json格式数据
- 查询contact字段的值
- 添加或减少contact字段的键值
- 按属性值进行查找
- 按匹配进行查找
下一篇:
Spring事务之事务超时和回滚规则