PostgreSql安装
-
apt-cache show postgresql:查看ubuntu可安装版本信息
-
sudo apt-get install postgresql:安装postgresql
-
提供了一个linux用户postgres
sudo su - postgres # 切换至postgres用户 psql --version # 查看版本 psql # 进入sql控制台 \q # 退出命令 ALTER USER postgres WITH PASSWORD 'postgres'; # 修改密码,默认密码是随机生成的
-
远程连接postgresql
# 默认端口号5432,用户名postgres,密码postgres sudo find / -name "pg_hba.conf" # 搜索配置文件位置 cd /etc/postgresql/10/main # 编辑配置文件,找到”IPv4 local connections:“,添加一行 # host all all 192.168.123.0/24 md5 sudo vim pg_hba.conf # 找到listen_addresses = 'localhost' # 改为listen_addresses = '*' sudo vim postgresql.conf # 重启数据库 service postgresql restart
简单数据库操作
psql -l # 查看数据库
createdb demo # 创建数据库
psql demo # 切换数据库
dropdb demo
help
select now();
select version();
# 创建表
create table posts(title varchar(255), content text);
\dt;
\d posts;
alter table posts rename to postsdemo;
drop table postsdemo;
# 编写.sql文件
psql demo
\i db.sql # 导入sql
create table posts (
id serial primary key,
title varchar(255) not null,
content text check(length(content) > 8),
is_draft boolean default TRUE,
is_del boolean default FALSE,
created_date timestamp default 'now'
);
insert into posts (title, content) values ('', '');
insert into posts (title, content) values (NULL, '');
insert into posts (title, content) values ('title1', 'content11');
select * from posts;
insert into posts (title, content) values ('title2', 'content2');
insert into posts (title, content) values ('title3', 'content3');
select * from posts;
create table users (
id serial primary key,
player varchar(255) not null,
score real,
team varchar(255)
);
insert into users (player, score, team) values
('阿A', 28.3, '勇士'),
('阿B', 30.2, '勇士'),
('阿C', 35.6, '勇士'),
('阿D', 27.8, '勇士'),
('阿E', 31.3, '勇士'),
('阿F', 19.8, '勇士');
# 不能用双引号括嘴外层
select * from users where player like '阿_'; # '_'表示一个数据
select * from users where player like '阿%';
select * from users order by score desc limit 3 offset 3;
select distinct team from user;
select team, max(score) from users group by team having max(score) >= 25 order by max(score);
# 方便的函数
length
concat
alias
substring
random
update users set score = 29.1 where ...
delete from user where ...
alter table users add fullname varchar(255);
alter table users drop fullname;
alter table users rename player to nba_player;
alter table users alter nba_player type varchar(100);
create index nba_player_index on users(nba_player);
drop index nba_player_index;
begin;
commit;
rollback;
字段类型
- 数值型:
- integer(int)
- real // 浮点
- serial // 序列型,如自增
- 文字型:
- char
- varchar
- text
- 布尔型:
- boolean
- 日期型:
- date
- time
- timestamp
- 特色类型:
- Array
- 网络地址型(inet)
- JSON
- XML
更多详情查看官网
网友评论