zoukankan      html  css  js  c++  java
  • psql-02基本语法

    客户端

    数据库:

    • 创建: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;
  • 相关阅读:
    linux系统编程程序员必备
    postgresql查询优化之GIN(Generalized Inverted Index)索引与全文检索
    postgresql并行执行
    lightdb for postgresql日志详解
    PostgreSQL 使用数组类型
    postgresql wal文件误删恢复
    汉语词性标注集
    postgresql----JSON类型、函数及全文检索的支持
    postgresql等待事件之wait_event为空解析
    lightdb for pg查看锁
  • 原文地址:https://www.cnblogs.com/jinkspeng/p/5010682.html
Copyright © 2011-2022 走看看