postgreSql基础
1 进入数据库
/home/pgadmin/psql shufu -U pgadmin
\dt 查看表:display table
\d 查看表结构
\q 退出数据库 quit
\c 切换数据库
2 数据类型
- varchar
- int(long)
- numeric
- date(timestamp)
3 数据库操作
3.0 模式
//建模式
create schema llf
//删除模式
drop schema llf cascade
//看数据库中已有模式
select * from information_schema.schemata;
\dns
//看模式中已有表
\dt llf.
//看模式下某类的表
\dt llf.*20170410*
\dt *20170410*
//看服务器上已有数据库
select * from pg_database;
3.1 创建表,删除表
# 创建表
create table example (
id int,
name varchar(50),
score numeric);
--基于已经有表复制表结构
create table example as
select * from td_action_20151120 limit 10000;
# 删除表
drop table llf.muying_key;
3.2 增删改数据
//增数据
insert into example values(1,'小李',90);
insert into example (id,name,score) select * from test;
//删数据
delete example where id=2;
//PostgreSQL删除重复数据
delete from emp where ctid not in (select min(ctid) from emp group by id);
https://www.cnblogs.com/mchina/archive/2013/04/15/3022086.html
//改数据
update example set score=100 where id=2;
3.3 改表结构
//修改数据库表名 PSQL :
alter table t rename to t1
alter table llf.test1 rename to test;
mysql: rename a to b
//修改列字段名
alter table t rename column a to b
//修改列字段数据类型
alter table t alter column a type text(50)
3.4 查询数据
select * from example order by log_count desc;
select time,imei,appnem from example limit 10;
select * from example where imei='456d45c8b912955139241385ec7ce4c4' limit 10;
--按条件过滤查询数据
where (A='' and B='') or C like '%aa%';
--去重
select distinct app_name from example;
# 表关联查询
select a.*,b.key1,key2
from example2 a,example_key b
where a.param_value like '%'||b.key1||'%' or a.param_value like '%'||b.key2||'%';
3.5 透视 分组汇总
select app_name,sum(log_count) as cc
from example
group by app_name order by cc desc;
--分组group by语句一般写法
select A,B,C,sum(a1*a3),sum(a2),count(*)
from TableA
where A='xx' and B='xx'
group by A,B,C;
4 数据入库和导出
4.1数据入库:
我们电脑 — 服务器 ----->>copy from >>—(数据库)
# 数据入库:csv只是格式,默认\t 分割
copy xx from '/xx/xx.csv'; #源文件是 \t 分割。
copy xx from '/xx/xx.csv' csv; #源文件是 逗号 分割。
copy example from '/home/score.csv' csv;
copy xx from '/xx/xx.csv' with delimiter '|'; # 源文件是 | 分割。
4.2 数据导出:
我们电脑 — 服务器 -----<<copy to <<—(数据库)
# 数据导出:在数据库里面查询到表copy到服务器,再从服务器下载到本地
copy (...) to '/home/pgadmin/shufu/appname_20151110.csv' csv;
copy (select a,b,c,sum(d) from table group by a,b,c) to '/home/myname_1.csv' csv;
5 psql函数
//时间戳-时间
to_char(to_timestamp(time),'yyyy-MM-dd')
// psql中/代表取整,如果保留小数需要类型转换::
postgres=# select round(23/24,2);
round
-------
0.00
(1 行记录)
postgres=#
postgres=# select round(23::numeric/24,2);
round
-------
0.96
(1 行记录)