postgresql学习笔记

postgresql学习笔记

概念

PostgreSQL是一个关系数据库管理系统,用于管理存储在关系中的数据的系统。开发面向对象的数据库。sql

每一个表都是命名的行集合。给定表的每一行都有相同的命名列表,每列都是特定的数据类型。尽管列在每行中都有固定的顺序,但重要的是记住SQL不能以任何方式保证表中行的顺序。数据库

表被分组到数据库中,由单个PostgreSQL服务器实例管理的数据库集合构成数据库集群。服务器

#函数

安装

官方下载安装,已同步onedrivepost

https://www.postgresql.org/学习

文档:https://www.postgresql.org/docs/11编码

系统是win10 64 
1.控制面板-用户帐户-> 添加用户postgres,并赋予管理员权限 spa

初始化:postgresql

initdb.exe -D d:\postgresql\data -E UTF-8 --locale=chs -U postgres -W对象

-D :指定数据库簇的存储目录E:\pgsql\data

-E :指定DB的超级用户的用户名postgres

--locale:关于区域设置(chinese-simplified-china)

-U :默认编码格式chs

-W :为超级用户指定密码的提示

启动服务:pg_ctl start

中止服务:pg_ctl stop

图形化界面:pgAdmin 4。须要先建立链接

环境变量PATH添加:D:\Software\PostgreSQL\bin

环境变量PGDATA添加:D:\Software\PostgreSQL\data

基本操做

数据库由客户端和服务器组成。

建立数据库:createdb -h localhost -U postgres mydb   默认用户名postgres

删除数据库:dropdb mydb

访问数据库:psql mydb。而后能够执行sql语句

建立新表

CREATE TABLE weather (
    city            varchar(80),
    temp_lo         int,
    temp_hi         int,
    prcp            real, 
    date            date
);

PostgreSQL支持基础类型

  1. int  整数类型
  2. smallint   小范围整数
  3. real   6位精度数据
  4. double   15位精度数据
  5. precision   任意精度数据
  6. char   字符
  7. varchar  字符串
  8. date  日期
  9. time   时间(无时区)
  10. timestamp   时间戳
  11. interval   时间间隔

删除表:DROP TABLE weather;

插入数据:insert into weather values('旧金山',0,0,null,'2019-01-06');

从平面文件加载:

COPY weather FROM'/home/user/weather.txt';

查询:SELECT * FROM weather ORDER BY city, temp_lo;

删除重复行:SELECT DISTINCT city FROM weather;

表链接:

SELECT weather.city, weather.temp_lo, weather.temp_hi,
       weather.prcp, weather.date, cities.location
    FROM weather, cities
    WHERE cities.name = weather.city;
SELECT *
    FROM weather INNER JOIN cities ON (weather.city = cities.name);
SELECT *
    FROM weather LEFT OUTER JOIN cities ON (weather.city = cities.name);

聚合函数:max(),不能使用在where中。可是能够结合GROUP BY HAVING

SELECT city, max(temp_lo)
    FROM weather
    WHERE city LIKE 'S%'            -- (1)
    GROUP BY city
    HAVING max(temp_lo) < 40;

更新:

UPDATE weather
    SET temp_hi = temp_hi - 2,  temp_lo = temp_lo - 2
    WHERE date > '1994-11-28';

删除:

DELETE FROM weather WHERE city = 'Hayward';

 

 

 

 

 

 

 

 

 

 

#