PostgreSQL

PostgreSQL Commands QuickStart:
[url]http://www.thegeekstuff.com/2009/04/15-practical-postgresql-database-adminstration-commands/[/url]
[url]http://www.linuxweblog.com/postgresql-reference[/url]

#查看 PostgreSQL 命令行工具的帮助,最有用的一个!!!!
\?
#重启 postgresql 服务 (ubuntu下)
$ sudo service postgresql restart
#登陆 PostgreSQL 命令行 (postgres 为其内置用户;这个默认的用户没有密码)
su - postgres
psql
#查看 SQL 语句的帮助
\h
#退出 PostgreSQL 命令行
\q
#列出所有库
\l
#切换数据库、用户等
\c[onnect] [DBNAME|- USER|- HOST|- PORT|-]
#查看当前库
select current_database();
#新建库
create database dbName;
#删除库
drop database dbName;
#列出当前库中的所有表
\d
#连接远程库 ( https://www.blog.akendo.eu/enable-remote-access-postgresql/ )
#如果连接被拒绝,参见 http://www.cyberciti.biz/faq/postgresql-remote-access-or-connection/
psql -h hostOfRemoteDB -U userOfRemoteDB -d nameOfRemoteDB
#查看所有用户
select * from pg_user;
查看当前用户是谁
select current_user;
#创建新用户
create user scott password 'tiger';
create user "www-data" password 'www-data'; //用户名中含特殊字符需用双引号引起来
#修改用户密码
\password
alter user postgres with password 'postgres';
#使某一用户拥有superuser角色,superuser对应的所有权限自然也赋给了该用户(当前用户需有权限做这个事,如默认的postgres)
alter user "www-data" with superuser;
# update query with join on two tables (http://stackoverflow.com/questions/2815953/update-query-with-join-on-two-tables)
UPDATE address
SET cid = customers.id
FROM customers
WHERE customers.id = address.id



PostgreSQL 9.2 Documentation:
[url]http://www.postgresql.org/docs/9.2/static/index.html[/url][quote]关于 Data Types - Numeric Types - Serial Types:
postgresql的Serial数据类型最终是通过sequence实现的,即:
CREATE TABLE tablename (
colname SERIAL
);
完全等价与:
CREATE SEQUENCE tablename_colname_seq;
CREATE TABLE tablename (
colname integer NOT NULL DEFAULT nextval('tablename_colname_seq')
);
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;
[/quote]


当使用某一用户连接提示 "Peer authentication failed for user" 时:
[url]http://blog.deliciousrobots.com/2011/12/13/get-postgres-working-on-ubuntu-or-linux-mint/[/url][quote]正确答案在该博文的评论里:
[b]You don't necessarily have to change the configuration. If you add -h 127.0.0.1 to the psql command it will connect through TCP instead of a Unix socket, in which case password authentication is used.[/b][/quote]


[b]shell脚本中执行psql,怎么免去输入密码的麻烦(psql command 没有提供输入密码的参数):[/b]
[url]http://stackoverflow.com/questions/6405127/how-do-i-specify-a-password-to-psql-non-interactively[/url]

#!/bin/bash

echo "localhost:*:*:www-data:www-data" > $HOME/.pgpass
echo "`chmod 0600 $HOME/.pgpass`"

psql -h localhost -U www-data -w -d email -c "delete from email_logging where receive_date <= current_timestamp - interval'10 days'"



[size=medium][color=red][b][align=center]CRUD[/align][/b][/color][/size]

alter table tab_name add unique (col_name);

postgresql paging:
select user_id,email from email_queue order by id limit 5000
select user_id,email from email_queue order by id offset 5001

INSERT INTO core_email_queue(user_id,email)
(SELECT user_id,email
FROM email_queue
order by id limit 5000 )

INSERT INTO target_email_queue(user_id,email)
(SELECT user_id,email
FROM email_queue
order by id offset 5001)

Remove duplicate:

----去除按某列dup_col的重复
delete from dup_table
where id not in
(
select min(dup.id)
from dup_table as dup
group by dup.dup_col
);
-----去除按col1,col2,col3的组合作为重复判断标准的重复
delete from dup_table
where id not in
(
select min(dup.id)
from dup_table as dup
group by dup.col1, dup.col2, dup.col3
);



remote server copy:[quote]
lee@ubuntu:~$ scp /home/qa.txt root@192.168.1.159:/root
lee@ubuntu:~$ ssh root@192.168.1.159
domU-00-16-3e-00-00-31 ~ # psql -U www-data zhoukan
//注意postgresql copy 命令的 from 路径不能是相对路径,如(当前用户root)这里写成 ‘~/qa.txt’ 是不行的!
zhoukan=# copy target_email_queue(user_id, email) from '/root/qa.txt' with csv;
qa.txt为以下格式的标准csv文档:
20463047,"bestyyz@hotmail.com"
4823001,"xueye_0511@163.com"
19544966,"lei_designcaa@163.com"
20443601,"ne.dingding@gmail.com"
19824195,"312743454@qq.com"
18351606,"kebei123@126.com"
787387,"wztwn@vip.sina.com"
6525245,"bsspirit@163.com"
13635170,"javahuangchengzhao@163.com"
8550177,"sinber@126.com"

[/quote]


[b]Postgresql 中的 Unique Index 和常见的用来加唯一约束的 unique constraint 的区别:[/b]
[url]http://www.postgresql.org/docs/9.2/static/indexes-unique.html[/url][quote]PostgreSQL [b]automatically creates a unique index when a unique constraint or primary key is defined for a table[/b]. The index covers the columns that make up the primary key or unique constraint (a multicolumn index, if appropriate), and is the mechanism that enforces the constraint.
[b]The preferred way to add a unique constraint to a table is ALTER TABLE ... ADD CONSTRAINT. The use of indexes to enforce unique constraints could be considered an implementation detail that should not be accessed directly. One should, however, be aware that there's no need to manually create indexes on unique columns; doing so would just duplicate the automatically-created index.(每个参与了 unique constraint 的列都会被隐式建立各自独立的 index,不需要再显式为这些列建立 index)[/b][/quote]


postgresql 中若使用了 distinct select, 则 order by 的列必须出现在 select 中,,否则会报 “for SELECT DISTINCT, ORDER BY expressions must appear in select list”,原因见:
[url]http://stackoverflow.com/questions/12693089/pgerror-select-distinct-order-by-expressions-must-appear-in-select-list[/url][quote] event_id | start_time
----------+------------------------
0 | Mar 17, 2013 12:00:00
1 | Jan 1, 1970 00:00:00
1 | Aug 21, 2013 16:30:00
2 | Jun 9, 2012 08:45:00
Now you want to grab a list of distinct event_ids, ordered by their respective start_times. But where should 1 go? Should it come first, because the one tuple starts on Jan 1, 1970, or should it go last because of the Aug 21, 2013?[/quote]
### PostgreSQL 安装、配置及使用方法 PostgreSQL 是一种功能强大的开源关系型数据库系统,支持 SQL 标准并具有高扩展性和可靠性。以下是关于 PostgreSQL 的安装、配置及使用方法的详细说明。 #### 1. 安装 PostgreSQL 在 CentOS 7 系统中,可以通过以下步骤完成 PostgreSQL 的安装: ```bash # 安装官方 YUM 仓库 sudo yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm # 安装 PostgreSQL 数据库服务器 sudo yum install -y postgresql10-server # 初始化数据库并设置自启动 sudo /usr/pgsql-10/bin/postgresql-10-setup initdb sudo systemctl enable postgresql-10 sudo systemctl start postgresql-10 ``` 上述命令将完成 PostgreSQL 的安装和初始化,并确保服务开机自启[^3]。 #### 2. 配置 PostgreSQL ##### 2.1 修改配置文件 PostgreSQL 的主要配置文件包括 `postgresql.conf` 和 `pg_hba.conf`。以下是两个文件的基本配置方法: - **postgresql.conf**:用于设置 PostgreSQL 的运行参数,例如监听地址、端口号等。 编辑 `postgresql.conf` 文件,修改以下内容以支持远程连接: ```plaintext listen_addresses = '*' # 允许所有 IP 地址访问 port = 5432 # 默认端口号 ``` - **pg_hba.conf**:用于定义客户端认证规则。 添加以下内容以允许特定 IP 地址通过密码认证访问: ```plaintext host all all 0.0.0.0/0 md5 ``` 上述配置表示允许来自任何 IP 地址的用户通过密码认证访问数据库[^2]。 ##### 2.2 重启服务 完成配置后,重启 PostgreSQL 服务以使更改生效: ```bash sudo systemctl restart postgresql-10 ``` #### 3. 使用 PostgreSQL ##### 3.1 创建用户和数据库 切换到 `postgres` 用户并进入 PostgreSQL 命令行工具: ```bash sudo su - postgres psql ``` 创建新用户和数据库: ```sql CREATE USER myuser WITH PASSWORD 'mypassword'; CREATE DATABASE mydb OWNER myuser; ``` ##### 3.2 连接数据库 退出 `psql` 并使用以下命令连接到指定数据库: ```bash psql -U myuser -d mydb ``` ##### 3.3 基本操作 以下是一些常用的 SQL 操作示例: - 创建表: ```sql CREATE TABLE employees ( id SERIAL PRIMARY KEY, name VARCHAR(100), salary NUMERIC(10, 2) ); ``` - 插入数据: ```sql INSERT INTO employees (name, salary) VALUES ('Alice', 5000.00); ``` - 查询数据: ```sql SELECT * FROM employees; ``` #### 4. 备份与恢复 ##### 4.1 数据备份 使用 `pg_dump` 工具生成数据库的 SQL 转储文件: ```bash pg_dump -U myuser -d mydb > backup.sql ``` ##### 4.2 数据恢复 将备份文件导入到目标数据库: ```bash psql -U myuser -d mydb < backup.sql ``` ### 注意事项 - 默认情况下,PostgreSQL 不允许远程连接,需要手动配置 `postgresql.conf` 和 `pg_hba.conf` 文件[^2]。 - 确保防火墙规则允许外部访问 PostgreSQL 的默认端口(5432)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值