1.链接数据库
psql -h Server -p Port -U Username DatabaseName算法
2.建立数据库
postgres=# create database testdb;sql
3.查看数据库
postgres=# \l数据库
4.删除数据库
postgres=# drop database testdb;ide
5.进入数据库
postgres=# \c testdb;函数
6.列出当前库全部表
testdb=# \dtpost
7.建立表
testdb=# create table account(
testdb(# user_id serial primary key,
testdb(# username varchar(50) unique not null,
testdb(# password varchar(50) not null);rest
create table products (
testdb(# product_no integer,
testdb(# name varchar(20),
testdb(# price numeric);postgresql
create table account (
username varchar(50) unique not null,
count integer);code
create table company(
ID int primary key not null,
name TEXT not null,
age int not null,
address char(50),
salary real
);对象
create table audit(
emp_id int not null,
entry_date text not null
);
8.删除表
testdb=# drop table account;
9.建立模式
testdb=# CREATE SCHEMA myschema;
10.指定模式建立表
create table myschema.mytable(
user_id serial primary key,
username varchar(50) unique not null,
password varchar(50) not null);
11.删除模式里的对象
drop schema myschema CASCADE;
12.删除模式
drop schema myschema
13.插入数据
testdb=# insert into products values (1, 'chiness', 9.99);
14.查询数据
testdb=# select * from products;
15.更新数据
testdb=# update products set name = 'hyh' where product_no = 1;
16.删除表数据
testdb=# delete from products where name = 'hyh'; 字符串必须单引号
17.order by 升序,降序排列
testdb=# select from products order by price asc;
testdb=# select from products order by price desc;
18.order by 多列排序
select * from products order by price,product_no asc;
19.group by分组
testdb=# select name, sum(price) from products group by name;
按名字分组统计每一个名字下的价格总额
20.HAVING子句与GROUP BY子句组合使用,用于选择函数结果知足某些条件的特定行
testdb=# select name from products group by name having name != 'hyh';
21.条件查询
AND 条件
testdb=# select * from products where name = 'hyh' and price = 10;
OR 条件
testdb=# select * from products where name = 'hyh' or price = 10;
AND & OR 条件
testdb=# select * from products where name = 'hyh' and price = 10 or product_no = 2;
NOT 条件
testdb=# select from products where name is not null;
testdb=# select from products where name not in ('hyh','chiness');
LIKE 条件
testdb=# select * from products where name like '%ch%';
IN 条件
testdb=# select * from products where price in (13,15);
NOT IN 条件
testdb=# select * from products where name not in ('hyh','chiness');
BETWEEN 条件
testdb=# select * from products where price between 10 and 15;
22.链接
内链接(INNER JOIN)
testdb=# select products.name,account.count from products inner join account on products.name = account.username;
左外链接(LEFT OUTER JOIN)
左外链接返回从“ON”条件中指定的左侧表中的全部行,只返回知足条件的另外一个表中的行
testdb=# select products.name,account.username,account.count from products left outer join account on products.price = account.count;
右外链接(RIGHT OUTER JOIN)
右外链接返回从“ON”条件中指定的右侧表中的全部行,只返回知足条件的另外一个表中的行
testdb=# select products.name,account.count from products right outer join account on products.name = account.username;
全链接(FULL OUTER JOIN)跨链接(CROSS JOIN)
全外链接从左表和右表中返回全部行。 它将NULL置于不知足链接条件的位置
testdb=# select products.name,account.count from products full outer join account on products.name = account.username;
23.建立函数
create or replace function totalRecords()
returns integer as $total$
declare
total integer;
begin
select count(*) into total from products;
return total;
end;
$total$ language plpgsql;
24.调用函数
select totalRecords();
25.触发器
PostgreSQL触发器是一组动做或数据库回调函数,它们在指定的表上执行指定的数据库事件(即,INSERT,UPDATE,DELETE或TRUNCATE语句)时自动运行。 触发器用于验证输入数据,执行业务规则,保持审计跟踪等
1.PostgreSQL在如下状况下执行/调用触发器:在尝试操做以前(在检查约束并尝试INSERT, UPDATE或DELETE以前)。或者在操做完成后(在检查约束而且INSERT,UPDATE或DELETE完成后)。或者不是操做(在视图中INSERT,UPDATE或DELETE的状况下)
2.对于操做修改的每一行,都会调用一个标记为FOR EACH ROWS的触发器。 另外一方面,标记为FOR EACH STATEMENT的触发器只对任何给定的操做执行一次,而无论它修改多少行。
3.您能够为同一事件定义同一类型的多个触发器,但条件是按名称按字母顺序触发。
4.当与它们相关联的表被删除时,触发器被自动删除
例子: 建立两个表 create table company( ID int primary key not null, name TEXT not null, age int not null, address char(50), salary real ); create table audit( emp_id int not null, entry_date text not null ); 建立函数 create or replace function auditlogfunc() returns trigger as $example_table$ begin insert into audit(emp_id, entry_date) values (new.id,current_timestamp); return new; end; $example_table$ language plpgsql; 建立触发器 create trigger example_trigger after insert on company for each row execute procedure auditlogfunc(); insert into company values(1,'小米科技',2,'北京清河',1234); #向company插入数据后,自动触发向audit表插入数据
26.索引
索引是用于加速从数据库检索数据的特殊查找表。数据库索引相似于书的索引(目录)。 索引为出如今索引列中的每一个值建立一个条目
数据库索引的重要特色:
索引使用SELECT查询和WHERE子句加速数据输出,可是会减慢使用INSERT和UPDATE语句输入的数据
您能够在不影响数据的状况下建立或删除索引
能够经过使用CREATE INDEX语句建立索引,指定建立索引的索引名称和表或列名称
还能够建立一个惟一索引,相似于惟一约束,该索引防止列或列的组合上有一个索引重复的索引
索引类型PostgreSQL中有几种索引类型,如B-tree,Hash,GiST,SP-GiST和GIN等。每种索引类型根据不一样的查询使用不一样的算法。 默认状况下,CREATE INDEX命令使用B树索引
在products表name字段建立索引(单列索引) create index products_index on products (name); 多列索引 create index account_index on account (username,count); 惟一索引,不容许表中出现重复的值 create unique index account_index on account (username); 删除索引 drop index account_index; 如下状况避免使用索引 应该避免在小表上使用索引。 不要为具备频繁,大批量更新或插入操做的表建立索引。 索引不该用于包含大量NULL值的列。 不要在常常操做(修改)的列上建立索引
28.union子句
PostgreSQL UNION子句/运算符用于组合两个或多个SELECT语句的结果,而不返回任何重复的行。
要使用UNION,每一个SELECT必须具备相同的列数,相同数量的列表达式,相同的数据类型,而且具备相同的顺序,但不必定要相同
SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID
UNION
SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;
union all 子句
SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID
UNION ALL
SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;
29.alter table
PostgreSQL ALTER TABLE命令用于添加,删除或修改现有表中的列。您还可使用ALTER TABLE命令在现有表上添加和删除各类约束
增长字段
alter table company add gender char(1);
删除字段
alter table company drop gender;
30.截断表 TRUNCATE TABLE
PostgreSQL TRUNCATE TABLE命令用于从现有表中删除完整的数据。您也可使用DROP TABLE命令删除完整的表,但会从数据库中删除完整的表结构,若是但愿存储某些数据,则须要从新建立此表。
它和在每一个表上使用DELETE语句具备相同的效果,但因为实际上并不扫描表,因此它的速度更快。 此外,它会当即回收磁盘空间,而不须要后续的VACUUM操做。 这在大表上是最有用的
truncate table company;
31.事务
事务具备如下四个标准属性,通常是由首字母缩写词ACID简称
原子性(Atomicity):确保工做单位内的全部操做成功完成; 不然事务将在故障点停止,之前的操做回滚到其之前的状态
一致性(Consistency):确保数据库在成功提交的事务时正确更改状态
隔离性(Isolation):使事务可以独立运做并相互透明
持久性(Durability):确保在系统发生故障的状况下,提交的事务的结果或效果仍然存在
如下命令用于控制事务:
BEGIN TRANSACTION:开始事务
COMMIT:保存更改,或者您可使用END TRANSACTION命令
ROLLBACK:回滚更改
回滚事务
testdb=# begin;
BEGIN
testdb=# delete from account where count = 10;
DELETE 1
testdb=# rollback;
ROLLBACK
提交事务
testdb=# begin;
BEGIN
testdb=# delete from account where count = 10;
DELETE 1
testdb=# commit;
COMMIT
testdb=# select * from account;
32.锁
锁或独占锁或写锁阻止用户修改行或整个表。 在UPDATE和DELETE修改的行在事务的持续时间内被自动独占锁定。 这将阻止其余用户更改行,直到事务被提交或回退。
用户必须等待其余用户当他们都尝试修改同一行时。 若是他们修改不一样的行,不须要等待。 SELECT查询没必要等待。
数据库自动执行锁定。 然而,在某些状况下,必须手动控制锁定。 手动锁定能够经过使用LOCK命令完成。 它容许指定事务的锁类型和范围
testdb=# lock table account in access exclusive mode;
33.子查询
子查询或内部查询或嵌套查询是一个PostgreSQL查询中的查询,它能够嵌入到WHERE子句中。子查询用于返回将在主查询中使用的数据做为进一步限制要检索的数据的条件。子查询能够与SELECT,INSERT,UPDATE和DELETE语句以及运算符(如=,<,>,>=,<=,IN等)一块儿使用。
子查询必须遵循如下规则:
1.子查询必须括在括号中
2.子查询在SELECT子句中只能有一列,除非主查询中有多个列用于比较其所选列的子查 询。ORDER BY不能用于子查询,尽管主查询可使用ORDER BY。 GROUP BY可 用于执行与 子查询中的ORDER BY相同的功能。
3.返回多行的子查询只能与多个值运算符一块儿使用,例如:IN,EXISTS,NOT IN,ANY / SOME,ALL运算符。
4.BETWEEN运算符不能与子查询一块儿使用; 可是,BETWEEN能够在子查询中使用
select子查询
select * from company where id in (select id from company where salary > 45000);
insert子查询插入数据
insert into company_bkp
select * from company
where id in (select id from company);
update 子查询修改数据
update company
set salary = salary * 0.50
where age in (select age from company_bkp where age >= 27);
delete子查询删除数据
delete from company
where age in (select age from company_bkp
where age > 27);
34.自增列
PostgreSQL具备数据类型smallserial,serial和bigserial; 这些不是真正的类型,而只是在建立惟一标识符列的标志以方便使用。 这些相似于一些其余数据库支持的AUTO_INCREMENT属性。
若是您但愿某列具备惟一的约束或是主键,则必须使用其余数据类型进行指定。
类型名称serial用于建立整数列。 类型名称bigserial建立一个bigint类型的列。 若是您指望在表的使用期限内使用超过2^31个标识符,则应使用bigserial。 类型名称smallserial建立一个smallint列
create table company(
id serial primary key, # 自增id name text not null,
age int not null,
address char(50),
salary real);
35.受权
建立用户
create user hyh with password '123456';
grant all on company to hyh; 给用户hyh授予company表的全部权限
取消受权
revoke all on company from hyh;
删除用户
drop user hyh;
36.重启psqlsystemctl restart postgresql-9.5.service