psql-02基本语法

本文档提供了 PostgreSQL 数据库的基础操作指南,包括数据库的创建、删除、连接、表的操作等,以及数据的增删改查等基本命令的使用。

客户端

数据库:
  • 创建:createdb mydb;
  • 删除: dropdb mydb;
连接:
  • 连接: psql mydb;
  • 断开连接: \q
  • 查看当前版本: select version();
  • 直接查看当前数据库情况: psql -l;
  • 在当前客户端下:
    • 跳转链接到其他数据库: \c mydb;
    • 创建新数据库: create database mydb;
表:
  • 所有表:\d;
  • 具体表: \d mytable //注意没有分号
  • 创建表:
create table mytable (
  col_name1  data_type1 [primary key],  //指定主键
  col_name2  data_type2
);
  • 删除表: drop table mytable;
  • 创建删除前加存在判断: 例子
创建数据
  • 插入数据: insert into mytable (col1, col2, ..) values (val1, val1, ...); //不指定字段的话,添加值按默认字段顺序储存;
  • 插入多条数据: insert into mytable values (....), (....);
  • 插入数据并返回结果: inser into mytable values(...) retruning col1,col2....|* ;
  • 更新: update mytable set col1 = val1, col2 = val2 where col3 = val3; //注意where衔接的不是逗号是and/or;
删除数据
  • delete from mytable where col1 = val1, col2 = val2;
  • 删除全部表数据
delete from mytable;  //相当于一条一条删除;
truncate table mytable;  //相当于一次性删除,比较快;
查找:
  • 查找所有: select */col1,col2.. from mytable where col1 = val1;
  • 查找排序显示:select * from mytable order by col1,col2.. //注意order by要放在where后面;
    • order by默认是ASC从小到大; 使用order by col1 DESC进行倒序排列;
  • 查找计算值: select max|min|sum|avg(attr) from users;
分组查询
  • 使用聚合函数(count/sum..), group by,按某个字段查找
select age, count(*) from student group by age;
多表关联查询
create table class(no int primaty key, class_name varchar(40) );
create table student(no int primary key, student_name varchar(40), age int, class_no int) );

//关联查询/表join

select student_name, class_name from student, class where student.class_no = class.no;

//简化
select student_name, class_name from student a, class b where a.class_no = b.no and a.age > 14;
拷贝数据
  • 使用insert into ... select: insert into tab1 select * from tab2 //注意tab2中要拷贝的字段tab1中都必须要有;
查询数据合并显示
select * from tab1 where col1 = val1 union select * from tab2 where col1 = val2;    //两个表必须要有相同的字段  
  • union默认会把过滤相同的查询结果;不过滤显示使用union all;

转载于:https://www.cnblogs.com/jinkspeng/p/5010682.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值