创建两个目录做表空间

mkdir /var/lib/pgsql/mydb_tbspace/

mkdir /var/lib/pgsql/java_tbspace/

创建表空间

postgres=# create tablespace fast_tb location '/var/lib/pgsql/mydb_tbspace';

CREATE TABLESPACE

postgres=# create tablespace java_tb location '/var/lib/pgsql/java_tbspace';

CREATE TABLESPACE

postgres=# \db
List of tablespaces
Name | Owner | Location
------------+----------+-----------------------------
fast_tb | postgres | /var/lib/pgsql/mydb_tbspace
java_tb | postgres | /var/lib/pgsql/java_tbspace
pg_default | postgres |
pg_global | postgres |
(4 rows)

创建表:

postgres=# create table test_tbs (id int, info text, crt_time timestamp) tablespace fast_tb;
CREATE TABLE
postgres=# \d test_tbs
Table "public.test_tbs"
Column | Type | Modifiers
----------+-----------------------------+-----------
id | integer |
info | text |
crt_time | timestamp without time zone |
Tablespace: "fast_tb"

postgres=# insert into test_tbs select generate_series(1, 100000), md5(random()::text), now();
INSERT 0 100000
postgres=# select test

postgres=# select * from test_tbs limit 10;
id | info | crt_time
----+----------------------------------+----------------------------
1 | 879828b62699ada2ef98ec5be3f8971a | 2017-05-19 11:07:41.970348
2 | f55a9abecfefbb462e10b974c09deb04 | 2017-05-19 11:07:41.970348
3 | 3f6017b8c324aba2b43eea5ad82ceb4f | 2017-05-19 11:07:41.970348
4 | ec2d1b1774b2a7a599f4e162447f9392 | 2017-05-19 11:07:41.970348
5 | b13686c413e91ddeec3291771966e70c | 2017-05-19 11:07:41.970348
6 | d1fd3d3e9889d9f4199b59c30655556f | 2017-05-19 11:07:41.970348
7 | 28185571d91fbe3fadbbbb2ab02ea8ca | 2017-05-19 11:07:41.970348
8 | 540937e17ad2102869208d1d748a0072 | 2017-05-19 11:07:41.970348
9 | ca9c323dc2c1c7cc8f808f5cae84a14c | 2017-05-19 11:07:41.970348
10 | e0ca51112bf1025af2dfe795c2d5c3f3 | 2017-05-19 11:07:41.970348
(10 rows)

查看表空间fast_tb:

-bash-4.1$ ls
16388 16396_fsm  16391 16393

-bash-4.1$ du -sh
7.4M .

改变表空间

postgres=# alter table test_tbs set tablespace java_tb ;
ALTER TABLE

postgres=# \d test_tbs
Table "public.test_tbs"
Column | Type | Modifiers
----------+-----------------------------+-----------
id | integer |
info | text |
crt_time | timestamp without time zone |
Tablespace: "java_tb"

查看新表空间:

-bash-4.1$ cd java_tbspace/PG_9.5_201510051/13241
-bash-4.1$ ls
16396 16396_fsm 16397 16398

-bash-4.1$ du -sh
7.4M .

原来表空间里面还文件,但是为空:

cd mydb_tbspace/PG_9.5_201510051/13241

-bash-4.1$ ls
16388 16391 16393

-bash-4.1$ du -sh
12K .

 
可以将一个表空间内表一起迁移到新表空间: 
ALTER TABLE ALL IN TABLESPACE pg_default SET TABLESPACE new_disk;
05-22 09:01