select*from users where age >20; # age 字段大于20 select*from users where age <30; # age 字段小于30 select*from users where age >20and age <30; # age 字段大于20且小于30 select*from users where department ='ple'; # department 字段等于ple select*from users where department !='ple'; # department 字段不等于ple select*from users where name like'zhang%'; # 以zhang开头 select*from users where name like'zhang_'; # 以zhang开头,后面仅一个字符
过滤后条目操作
使用select语句过滤数据后,再对数据进行更多选项操作(如排序,随机抽选)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# order 排序 asc升序 desc降序 select*from users orderby age asc; select*from users orderby age desc; select*from users orderby department; select*from users orderby department, age; select*from users orderby department, age desc; select*from users orderby department desc, age desc;
# limit 从头取多少个 select*from users orderby age desc limit 3;
# offset 排序偏移 select*from users orderby age desc limit 3offset1; select*from users orderby age desc limit 3offset2; select*from users orderby age desc limit 3offset3;
过滤后条目计算
distinct 去重
sum 加计算
max/ min 找最大/最小
group by/ having 分组/ 分组过滤条件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#列出所有department,并去重复 selectdistinct department from users;
# 计算出所有人salary总和 selectsum(salary) from users;
# 取出salary最大或最小值 selectmax(salary) from users; selectmin(salary) from users;
# 取出age最大或最小的一行条目 select*from users where age = (selectmax(age) from users); select*from users where age = (selectmin(age) from users);
# 以department来分组,取出每个组age最大的 select department, max(age) from users groupby department;
# 以department来分组,组内salary的最大值如果不大于5000,过滤掉 select department, max(salary) from users groupby department havingmax(salary) >5000;
# users表的name,和notes表的content根据user_id关联,然后取出 select users.name, notes.content from users, notes where users.id = notes.user_id;
# 添加别名,减少代码数 select u."中文名", n.content from users as u, notes as n where u.id = n.user_id;
# 只提出user_id=1的notes select u."中文名", n.content from users as u, notes as n where u.id = n.user_id and u.id=1;
视图
create view
drop view
View视图可以理解为一个SELECT语句,将项目中常用的SELECT语句简化成一个虚拟表对象。
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# 创建视图,视图的名称为 zhangly_notes # as后的语句则是过滤条件 createview zhangly_notes asselect u.name, n.content from users as u, notes as n where u.id = n.user_id and u.name='zhangly';
begin; //开始事务 update users set department ='lay'where name ='zhangly'; //进行一些更新 update users set department ='lay'where name ='yanyan'; update users set department ='lay'where name ='liyc'; commit; //执行到这一步的时候,才会进行实际的更新操作
# 回滚操作
begin; update users set department ='pmd'where name ='zhangly'; //进行一些更新 update users set department ='ani'where name ='yanyan'; update users set department ='cfx'where name ='liyc'; rollback; //回滚到事务开始,也就是删除上述的预更新
备份和恢复
pg_dump 备份单个数据库
pg_dumpall 备份所有数据库
pg_restore 恢复数据库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 备份数据库,需要退出交互模式下进行
pg_dump mydb > mydb.bak pg_dump -f /tmp/mydb.bak mydb pg_dump - F t /tmp/postgres.tar mydb # 指定为tar压缩格式