支持的系统:Linux, UNIX (AIX, BSD, HP-UX, SGI IRIX, Mac OS X, Solaris, Tru64), and Windows.
功能:has full support for foreign keys, joins, views, triggers, and stored procedures.
数据类型:It includes most SQL:2008 data types, including INTEGER, NUMERIC, BOOLEAN, CHAR, VARCHAR, DATE, INTERVAL, and TIMESTAMP. It also supports storage of binary large objects, including pictures, sounds, or video.此外,用户可以创建自定义数据类型,通常通过PostgreSQL的GiST机制,它们也能被很好得索引,比如PostGIS地理信息系统的数据类型.
语言支持:It has native programming interfaces for C/C++, Java, .Net, Perl, Python, Ruby, Tcl, ODBC, among others, and exceptional documentation.
2. 登录 psql -h host -U user -d database_name -p port
PostgreSQL默认端口为5432,-d参数指定数据库名称:
1234
xiaobaoqiu@xiaobaoqiu:/var/run/postgresql$ psql -h localhost -U postgres
Password for user postgres:
psql.bin (9.3.4)
Type "help" for help.
3. 退出
1
\q
4. 所有用户
12345
postgis_template=# \du
List of roles
Role name | Attributes | Member of
-----------+------------------------------------------------+-----------
postgres | Superuser, Create role, Create DB, Replication | {}
4. 连接信息
12
postgres=# \conninfo
You are connected to database "postgres" as user "postgres" on host "localhost" at port "5432".
4. show databases
12345
hotel=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
---------------------+----------+----------+------------+------------+-----------------------
fb_stat | postgres | UTF8 | en_US.utf8 | en_US.utf8 |
5. switch database
12
postgres=# \c postgis_template
You are now connected to database "postgis_template" as user "postgres".
6. show tables
\d 显示所有表
1234567891011
postgis_template=# \d
List of relations
Schema | Name | Type | Owner
----------+-------------------+----------+----------
public | geography_columns | view | postgres
public | geometry_columns | view | postgres
public | spatial_ref_sys | table | postgres
topology | layer | table | postgres
topology | topology | table | postgres
topology | topology_id_seq | sequence | postgres
(6 rows)
\d table_name
1234567891011
postgis_template=# \d geography_columns
View "public.geography_columns"
Column | Type | Modifiers
--------------------+---------+-----------
f_table_catalog | name |
f_table_schema | name |
f_table_name | name |
f_geography_column | name |
coord_dimension | integer |
srid | integer |
type | text |
# 创建表
CREATE TABLE user_tbl(name VARCHAR(20), signup_date DATE);
# 插入数据
INSERT INTO user_tbl(name, signup_date) VALUES('张三', '2013-12-22');
# 选择记录
SELECT * FROM user_tbl;
# 更新数据
UPDATE user_tbl set name = '李四' WHERE name = '张三';
# 删除记录
DELETE FROM user_tbl WHERE name = '李四' ;
# 添加列
ALTER TABLE user_tbl ADD email VARCHAR(40);
# 更新表结构
ALTER TABLE user_tbl ALTER COLUMN signup_date SET NOT NULL;
# 更名列
ALTER TABLE user_tbl RENAME COLUMN signup_date TO signup;
# 删除列
ALTER TABLE user_tbl DROP COLUMN email;
# 表格更名
ALTER TABLE user_tbl RENAME TO backup_tbl;
# 删除表格
DROP TABLE IF EXISTS backup_tbl;
8. PostgreSQL Client支持的一些命令(直接在shell运行):
1234567891011121314151617
clusterdb -- cluster a PostgreSQL database
createdb -- create a new PostgreSQL database
createlang -- install a PostgreSQL procedural language
createuser -- define a new PostgreSQL user account
dropdb -- remove a PostgreSQL database
droplang -- remove a PostgreSQL procedural language
dropuser -- remove a PostgreSQL user account
ecpg -- embedded SQL C preprocessor
pg_basebackup -- take a base backup of a PostgreSQL cluster
pg_config -- retrieve information about the installed version of PostgreSQL
pg_dump -- extract a PostgreSQL database into a script file or other archive file
pg_dumpall -- extract a PostgreSQL database cluster into a script file
pg_receivexlog -- streams transaction logs from a PostgreSQL cluster
pg_restore -- restore a PostgreSQL database from an archive file created by pg_dump
psql -- PostgreSQL interactive terminal
reindexdb -- reindex a PostgreSQL database
vacuumdb -- garbage-collect and analyze a PostgreSQL database
Los Angeles: POINT(-118.4079 33.9434)
Paris: POINT(2.3490 48.8533)
#距离
SELECT ST_Distance(
ST_GeometryFromText('POINT(-118.4079 33.9434)', 4326), -- Los Angeles (LAX)
ST_GeometryFromText('POINT(2.5559 49.0083)', 4326) -- Paris (CDG)
);
121.898285970107度
#距离米
SELECT ST_Distance(
ST_GeographyFromText('POINT(-118.4079 33.9434)'), -- Los Angeles (LAX)
ST_GeographyFromText('POINT(2.5559 49.0083)') -- Paris (CDG)
);
9124665.26917268米
Geometry :几何坐标
1234567891011121314151617181920
ST_AsText
#点
ST_X ST_Y
#线
ST_Length 线长度
ST_StartPoint 起点
ST_EndPoint 终点
ST_NPoints 点数
#多边形
ST_Area(geometry)面积
ST_NRings(geometry)环个数
ST_ExteriorRing(geometry) 外接环
ST_InteriorRingN(geometry,n) 内接环
ST_Perimeter(geometry) 所有环的长度
#集合
MultiPoint, a collection of points
MultiLineString, a collection of linestrings
MultiPolygon, a collection of polygons
GeometryCollection, a heterogeneous collection of any geometry (including other collections)
SELECT id, name, city_code, st_astext(gpoint) FROM poi
WHERE ST_DWithin(GeomFromText('POINT(117.28243891065 39.096105298613)',4326), gpoint, 1000)
ORDER BY ST_Distance(GeomFromText('POINT(117.28243891065 39.096105298613)',4326), gpoint)
LIMIT 10;
mysql> show variables like 'log_bin';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| log_bin | ON |
+---------------+-------+
1 row in set (0.00 sec)
mysql> set global max_binlog_size=1024*1024;
Query OK, 0 rows affected (0.00 sec)
mysql> show variables like 'max_binlog_size';
+-----------------+---------+
| Variable_name | Value |
+-----------------+---------+
| max_binlog_size | 1048576 |
+-----------------+---------+
1 row in set (0.00 sec)
mysql> show variables like 'expire_logs_days';
+------------------+-------+
| Variable_name | Value |
+------------------+-------+
| expire_logs_days | 10 |
+------------------+-------+
1 row in set (0.00 sec)
配置在my.cnf文件中:
1
expire_logs_days = 10
我们也可以改变这个参数(必须管理员权限):
12345678910
mysql> set global expire_logs_days=3;
Query OK, 0 rows affected (0.00 sec)
mysql> show variables like 'expire_logs_days';
+------------------+-------+
| Variable_name | Value |
+------------------+-------+
| expire_logs_days | 3 |
+------------------+-------+
1 row in set (0.00 sec)
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=1*/;
/*!40019 SET @@session.max_insert_delayed_threads=0*/;
/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;
DELIMITER /*!*/;
# at 4
#140524 14:15:56 server id 1 end_log_pos 107 Start: binlog v 4, server v 5.5.34-0ubuntu0.13.04.1-log created 140524 14:15:56
BINLOG '
HDmAUw8BAAAAZwAAAGsAAAAAAAQANS41LjM0LTB1YnVudHUwLjEzLjA0LjEtbG9nAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAEzgNAAgAEgAEBAQEEgAAVAAEGggAAAAICAgCAA==
'/*!*/;
# at 107
#140524 15:10:44 server id 1 end_log_pos 218 Query thread_id=38 exec_time=0 error_code=0
use `test`/*!*/;
SET TIMESTAMP=1400915444/*!*/;
SET @@session.pseudo_thread_id=38/*!*/;
SET @@session.foreign_key_checks=1, @@session.sql_auto_is_null=0, @@session.unique_checks=1, @@session.autocommit=1/*!*/;
SET @@session.sql_mode=0/*!*/;
SET @@session.auto_increment_increment=1, @@session.auto_increment_offset=1/*!*/;
/*!\C utf8 *//*!*/;
SET @@session.character_set_client=33,@@session.collation_connection=33,@@session.collation_server=8/*!*/;
SET @@session.lc_time_names=0/*!*/;
SET @@session.collation_database=DEFAULT/*!*/;
DROP TABLE `order_log` /* generated by server */
/*!*/;
...
# at 461
#140524 15:11:07 server id 1 end_log_pos 576 Query thread_id=38 exec_time=0 error_code=0
SET TIMESTAMP=1400915467/*!*/;
DROP TABLE `qbooking_role` /* generated by server */
/*!*/;
# at 576
#140524 15:11:17 server id 1 end_log_pos 700 Query thread_id=38 exec_time=0 error_code=0
SET TIMESTAMP=1400915477/*!*/;
DROP TABLE `qbooking_role_resource` /* generated by server */
/*!*/;
# at 700
#140524 15:11:22 server id 1 end_log_pos 815 Query thread_id=38 exec_time=0 error_code=0
SET TIMESTAMP=1400915482/*!*/;
DROP TABLE `qbooking_user` /* generated by server */
/*!*/;
我们以其中的一个片段来解析:
12345
# at 576
#140524 15:11:17 server id 1 end_log_pos 700 Query thread_id=38 exec_time=0 error_code=0
SET TIMESTAMP=1400915477/*!*/;
DROP TABLE `qbooking_role_resource` /* generated by server */
/*!*/;
简单解析如下:
1234567891011
# at 576 : 说明这个事件的起点,从576个字节开始的;
#140524 15:11:17 : 表明事件发生的时间戳为2014-05-24 15:11:17;
server id 1 : 事件发生的服务器的标识id;
end_log_pos 700 : 事件的终点,下一个事件从第700个字节开始;
Query : 事件类型,mysql中的insert、update、delete都是属于query;
thread_id=38 : 执行事件的线程
exec_time=0 : 执行命令花费的时间
error_code=0 : 执行命令的错误码
SET TIMESTAMP=1400915477/*!*/; : 命令的时间戳
DROP TABLE `qbooking_role_resource` /* generated by server */ : 命令
/*!*/; : 结束
mysql> show variables like 'binlog_format';
+---------------+-----------+
| Variable_name | Value |
+---------------+-----------+
| binlog_format | STATEMENT |
+---------------+-----------+
1 row in set (0.00 sec)
Usage: mysqlbinlog [options] log-files
-?, --help 显示帮助文档
--base64-output[=name]
Determine when the output statements should be
base64-encoded BINLOG statements: 'never' disables it and
works only for binlogs without row-based events;
'decode-rows' decodes row events into commented SQL
statements if the --verbose option is also given; 'auto'
prints base64 only when necessary (i.e., for row-based
events and format description events); 'always' prints
base64 whenever possible. 'always' is deprecated, will be
removed in a future version, and should not be used in a
production system. --base64-output with no 'name'
argument is equivalent to --base64-output=always and is
also deprecated. If no --base64-output[=name] option is
given at all, the default is 'auto'.
--character-sets-dir=name
Directory for character set files.
-d, --database=name 指定数据库,只显示这个数据库的数据(只用于本地).
--debug-check 退出时候检查内存和已打开文件的使用.
--debug-info 退出的时候打印debug信息
--default-auth=name Default authentication client-side plugin to use.
-D, --disable-log-bin
Disable binary log. This is useful, if you enabled
--to-last-log and are sending the output to the same
MySQL server. This way you could avoid an endless loop.
You would also like to use it when restoring after a
crash to avoid duplication of the statements you already
have. NOTE: you will need a SUPER privilege to use this
option.
-F, --force-if-open 即使出现SQL错误也继续
Force if binlog was not closed properly.
(Defaults to on; use --skip-force-if-open to disable.)
-f, --force-read Force reading unknown binlog events.
使用该选项,如果mysqlbinlog读它不能识别的二进制日志事件,它会打印警告,忽略该事件并继续。没有该选项,如果mysqlbinlog读到此类事件则停止。
-H, --hexdump Augment output with hexadecimal and ASCII event dump.
在注释中显示日志的十六进制转储。该输出可以帮助复制过程中的调试。
-h, --host=name Get the binlog from server.主机名
-l, --local-load=name
为指定目录中的LOAD DATA INFILE预处理本地临时文件
Prepare local temporary files for LOAD DATA INFILE in the
specified directory.
-o, --offset=# 跳过前N个条目,Skip the first N entries.
-p, --password[=name]
连接远程服务器的密码,Password to connect to remote server.
--plugin-dir=name Directory for client-side plugins.
-P, --port=# 用于连接远程服务器的TCP/IP端口号
Port number to use for connection or 0 for default to, in
order of preference, my.cnf, $MYSQL_TCP_PORT,
/etc/services, built-in default (3306).
--protocol=name 使用的连接协议,如TCP | SOCKET | PIPE |
The protocol to use for connection (tcp, socket, pipe,
memory).
-R, --read-from-remote-server
从MySQL服务器读二进制日志。如果未给出该选项,任何连接参数选项将被忽略:--host、--password、--port、--protocol、--socket和--user。
Read binary logs from a MySQL server.
-r, --result-file=name
将输出指向给定的文件
Direct output to a given file.
--server-id=# Extract only binlog entries created by the server having
the given id.
--set-charset=name 输出的时候设置SET NAMES character_set,Add 'SET NAMES character_set' to the output.
-s, --short-form 只显示日志中包含的语句,不显示其它信息,
Just show regular queries: no extra info and no row-based
events. This is for testing only, and should not be used
in production systems. If you want to suppress
base64-output, consider using --base64-output=never
instead.
-S, --socket=name The socket file to use for connection.
--start-datetime=name
从二进制日志中第1个日期时间等于或晚于datetime参量的事件开始读取。datetime值相对于运行mysqlbinlog的机器上的本地时区。该值格式应符合DATETIME或TIMESTAMP数据类型。如“2004-12-25 11:25:56”
Start reading the binlog at first event having a datetime
equal or posterior to the argument; the argument must be
a date and time in the local time zone, in any format
accepted by the MySQL server for DATETIME and TIMESTAMP
types, for example: 2004-12-25 11:25:56 (you should
probably use quotes for your shell to set it properly).
-j, --start-position=#
从二进制日志中第1个位置等于N参量时的事件开始读。
Start reading the binlog at position N. Applies to the
first binlog passed on the command line.
--stop-datetime=name
从二进制日志中第1个日期时间等于或晚于datetime参量的事件起停止读。
Stop reading the binlog at first event having a datetime
equal or posterior to the argument; the argument must be
a date and time in the local time zone, in any format
accepted by the MySQL server for DATETIME and TIMESTAMP
types, for example: 2004-12-25 11:25:56 (you should
probably use quotes for your shell to set it properly).
--stop-position=# 从二进制日志中第1个位置等于和大于N参量时的事件起停止读
Stop reading the binlog at position N. Applies to the
last binlog passed on the command line.
-t, --to-last-log 在MySQL服务器中请求的二进制日志的结尾处不停止,而是继续打印直到最后一个二进制日志的结尾。如果将输出发送给同一台MySQL服务器,会导致无限循环。该选项要求--read-from-remote-server。
Requires -R. Will not stop at the end of the requested
binlog but rather continue printing until the end of the
last binlog of the MySQL server. If you send the output
to the same MySQL server, that may lead to an endless
loop.
-u, --user=name 连接远程服务器的用户名,Connect to the remote server as username.
-v, --verbose 对于ROW event重新构造SQL语句。
Reconstruct SQL statements out of row events. -v -v adds
comments on column data types.
-V, --version 版本信息,Print version and exit.
--open-files-limit=#
Used to reserve file descriptors for use by this program.
如何使用复制提高系统性能:配置一个master服务器只用于写,配置尽可能多的slave服务器,将读操作分到各个master和slave之间。同时,我们可以使用–skip-innodb(不使用InnoDB storage engine), –low-priority-updates(将INSERT, REPLACE, DELETE, UPDATE这些修改操作的优先级设置得比SELECT低)和–delay-key-write=ALL(Delayed key writing causes key buffers not to be flushed between writes for MyISAM tables)选项来启动salve达到加速slave的目的,这样就可以使用非事务的MyISAM表代替InnoDB表,排除了事物的代价从而更快速。