在PostgreSQL中如何用簡單的幾條SQL語句生成大量的測試數據呢?
此處,我簡單的寫一個例子,經過測試的:
(1)准備知識
針對 Postgres生成數據方法
<1>生成序列====》 SELECT * FROM generate_series(1,5);
<2>生成date====》 SELECT date(generate_series(now(), now() + '1 week', '1 day'));
<3>生成integer 隨機數=》 SELECT (random()*(2*10^9))::integer;
<4>生成numeric 隨機數=》select (random()*100)::numeric(4,2);
<5>生成字符串==》 select substr('abcdefghijklmnopqrstuvwxyz',1,(random()*26)::integer);
<6>生成重復串==> select repeat('1',(random()*40)::integer);
舉例:
SELECT generate_series(1,10) as key,(random()*100.)::numeric(4,2),repeat('1',(random()*25)::integer) ORDER BY random();
key | numeric | repeat
-----+---------+--------------------------
8 | 26.04 | 111
10 | 83.44 | 1
9 | 46.72 |
3 | 57.84 | 1111111111111
4 | 29.61 | 1111111111111111111
5 | 11.32 | 1111111111111
7 | 69.69 |
2 | 42.23 | 11111111111111111
6 | 12.32 | 111111111111111111111111
1 | 84.92 | 111111二、
如果您想知道執行該sql的時間,請在執行上述命令前設置:
postgres=# \timing on
Timing is on.(1)測試參考SQL,可以把生成的隨機值改的大一些;
#生成新表===>
select i,'text:'||i as text into test from generate_series(1,10) as i;
#在新表中插入測試數據===>
insert into test(i,text) select i,'text:'||i from generate_series(1,10) as i;
(2)查看表test占用的存儲空間
![]()
若查看其中的index的空間或整個relation的空間,請參考:
http://www.postgresql.org/docs/9.1/static/functions-admin.html
或:http://www.postgresql.org/docs/9.1/static/functions-admin.html
(3)查看整個數據庫占用的硬盤空間:
(4)如果想用delete清空該表,然后真正清空硬盤空間
從上面的步驟可以看出,vacuumdb后空間回收數據又減少到最初的6.9M的空間了。
參考自:http://blog.csdn.net/cool_cr/article/details/31745145

