一: 访问数据
1: psql的使用
psql --help 查看命令行使用帮助
eg: psql连接数据库例子:
psql -h 127.0.0.1 -p 12345 -U postgres -d postgres
2: 使用select语句
(1)查看select 语法:
postgres=# \h select
(2) select 常用语法介绍
[1] 别名
postgres=# select 'nihao' as col_alias ----列别名
from table_name as t ---源别名
limit 1;
[2] 字段、函数、表达式、子查询
postgres=# select relname, ---列名
now(), -----函数
upper(relname)||'__digoal', ----表达式
(select 1+2+3)---子查询
from pg_classs limit 2;
[3] 表、视图、物化视图、函数、表达式、子查询
select * from 表;
select * from 视图;
select * from 物化视图;
select * from 函数(参数);
select * from 函数(参数) as t(列1 类型1,... , 列n 类型n);
select 表达式;
select (子查询) as t;
[4] select where条件、排序、随机排序、分组、限制输出、位移
select relname, reltuples from pg_class where relname = 'pg_class';
select oid, relname from pg_class order by oid limit 1;
select oid, relname from pg_class order by random() limit 1;
select relkind, count(*) from pg_class group y relkind;
select relkind, count(*) from pg_class group y relkind limit 1;
select relkind, count(*) from pg_class group y relkind order by relkind offset 1 limit 1;
3:使用游标
[1] 创建游标、fetch游标、关闭游标
postgres=# begin;
postgres=# declare cur1 cursor for select oid, relname, relkind from pg_class;
postgres=# fetch 2 form cur1;
postgres=# close cur1;
4: 行表达式
postgres=# select * from (values(1, 'test1'), (2, 'test2')) as t(id, info);
5: with
(1) with 语句:
postgres=# with
a as (select * from (values(1,'test1'),(2,'test2'),(3,'test3')) as t(id, info)),
b as (select oid,relname,relkind from pg_class)
select a.*,b.* from a,b where a.id=mod(b.oid::int,3)+1;
6: 执行ddl\dml\dcl
[1] 建表
create table tb1(id int, info text, crt_time, timestamp);
[2] 插入(增)
insert into tb1 (id, info, crt_time) values (1, 'test', now());
[3] 批量插入
insert into tb1 (id, info, crt_time) select generate_series(1, 10000), 'test', now(); // 批量插入
insert into tb1 (id, info, crt_time) values (1, 'test', now()), (2, 'test', now()), (3, 'test', now()); // 批量插入
begin;
insert into tb1 (id, info, crt_time) values (1, 'test', now());
insert into tb1 (id, info, crt_time) values (2, 'test', now());
insert into tb1 (id, info, crt_time) values (3, 'test', now());
end; // 批量插入
[4] 更新
update tb1 set info = 'new' where id =1;