PostgreSQL各數據類型的內置函數


參考《PostgreSQL實戰》

3.1.2 數字類型操作符和數學函數

PostgreSQL 支持數字類型操作符和豐富的數學函數

例如支持加、減、乘、除、模取取余操作符

SELECT 1+2, 2*3, 4/2, 8%3;

按模取余

SELECT mod(8,3);
結果:2

四舍五入函數:

SELECT round(10.4) , round(10.5);
結果:10, 11

返回大於或等於給出參數的最小整數

SELECT ceil(3.6) , ceil(-3.6);
結果:4, -3

返回小於或等於給出參數的最小整數

floor(3.6) 結果:3

3.2.2 字符類型函數

PostgreSQL 支持豐富 的字符函數, 下面舉例說明

計算字符串中的字符數

select char_length('abcd');
結果: 4

計算字符串占用的字節數

select octet_length('abcd');
結果: 4

指定字符在字符串中的位置(首次出現)

select position('a' in 'abcda')
結果: 1
select position('x' in 'abcda')
結果: 0

提取字符串中的子串

select substring('hello' from 3 for 4)
結果: llo
select substring('hello' from 4 for 1)
結果: l

拆分字符串

split_part (string text, delimiter text, field int )

根據 delimiter 分隔符拆分字符串 string,並返回指定字段,字段從 1 開始

select split_part('abc@def1@nb', '@', 1)
結果: abc

3.3.2 時間/日期類型操作符

時間 、 日期數據類型支持的操作符有加、減、乘、 除

日期相加

select date '2017-07-29' + interval'1 days'
結果: 2017-07-30 00:00:00

日期相減

select date '2017-07-29' - interval'1 hour'
結果: 2017-07-28 23:00:00

日期相乘

select 100* interval '1 second'
結果: 00:01:40

日期相除

select interval '1 hour' / double precision '3'
結果: 00:20:00

3.3.3 時間/日期類型常用函數

顯示當前時間

select current_date, current_time;
結果: 2019-11-23, 20:20:55.635115+08

另一個非常重要的函數為 EXTRACT 函數,可以從日期 、 時間數據類型中抽取年、月、日、 時、分、秒信息

EXTRACT(field FROM source)

field 值可以為 century、year、 month、 day、 hour 、 minute、 second等, source類型為
timestamp、 time、 interval的值的表達式。

取年份

select extract ( year from now())
結果: 2019

月份&月份里的第幾天(當前時間2019-11-24)

select extract (month from now()), extract(day from now());
結果: 11, 24

抽取小時、分鍾、秒語法同上,單詞為hour,minute,second

抽取當前日期是所在年份的第幾周&多少天

select extract(week from now()), extract(day from now())
結果: 47, 24

3.5.3 網絡地址函數

PostgreSQL 網絡地址類型支持一系列內置函數,下面舉例說明。

取IP地址 , 返回文本格式。

select host(cidr '192.168.1.0/24');
結果: 192.168.1.0

取IP地址和網絡掩碼,返回文本格式

select text(cidr '192.168.1.0/24');
結果: 192.168.1.0/24

網絡地址子網掩碼,返回文本格式

select netmask(cidr '192.168.1.0/24');
結果: 255.255.255.0

3.6.4 數據元素的追加、刪除、更新

數組元素的追加使用array_append 函數

array_append(anyarray, anyelement)

array_append 函數向數組末端追加一個元素

select array_append(array[1,2,3], 4);
結果: {1,2,3,4}

數據元素追加到數組也可以使用操作符 ||

select array[1,2,3] || 4;
結果: {1,2,3,4}

數組元素的刪除使用 array_remove 函數

array_remove(anyarray, anyelement)

array_remove 函數將移除數組中值等於給定值的所有數組元素

select array[1,2,2,3], array_remove(array[1,2,2,3], 2);
結果: {1,2,2,3}, {1,3}

數組元素修改:

update test_array_table set array_i[3] = 4 where id = 1;
UPDATE 1

更新整個數組

update test_array_table set array_i=array[7,8,9] where id = 1;
UPDATE 1

3.6.5 數組操作符

數組操作符

3.6.6 數組函數

數組維度

select array_ndims(array[1,2]);
結果: 1

數組長度(獲取指定維度的長度)

select array_length(array[1,2], 1);
結果: 2

select array_length(array[[1],[2]], 2);
結果: 1
select array_length(array[[1],[2]], 1);
結果: 2

返回數組中某個數組元素第一次出現的位置

select array_position(array['a', 'b', 'c', 'd'], 'd');
結果: 4

數組元素替換可使用函數 array_replace

array replace(anyarray, anyelement, anyelement)

函數返回值類型為 anyarray,使用第二個 anyelement 替換數組中的相同數組元素

select array_replace( array[1,2,3,3,4], 3, 6);
結果: {1,2,6,6,4}

將數組元素輸出到字符串,可以使用 array_to_string 函數

array_to_striiing( anyarray, text [, test])

函數返回值類型為text ,第一個text 參數指分隔符,第二個 text 表示將值為 NULL 的
元素使用這個字符串替換

select array_to_string(array[1,2,null,3], ',', '-1');
結果: 1,2,-1,3

還有array_to_json(array)函數,將數組直接轉換為json

3.7.4 范圍類型函數

以下列舉范圍類型常用函數

取范圍下界

select lower(int4range(1,10));
結果: 1

取范圍上界

select upper(int4range(1,10));
結果: 10

范圍是否為空

select isempty(int4range(1,10));
結果: f
select isempty(int4range(10,10));
結果: t

3.8.5 jsonb與json函數

json 與 jsonb 相關的函數非常豐富, 下面舉例說明

擴展最外層的 json 對象成為一組鍵/值結果集

select * from json_each('{"a":"foo", "b":"bar"}');
結果:
a | "foo"
b | "bar"

文本形式返回結果

select * from json_each_text('{"a":"foo", "b":"bar"}');
結果:
a |	foo
b |	bar

row_tojson()函數,能夠將行作為json對象返回。
此函數常用來生成 json 測試數據,比如將一個普通表轉換成 json 類型表

select * from test_copy where id = 1;

id | name
---+-----
1  | a

select row_to_json(test_copy) from test_copy where id = 1;

row_to_json
--------------
{"id":1,"name":"a"}

返回最外層的 json 對象中的鍵的集合

select * from json_object_keys('{"a":"foo", "b":"bar"}');

json_object_keys
---------------
a
b

3.8.6 jsonb 鍵/值的追加、刪除、更新

jsonb 鍵/值追加可通過“||”操作符

select '{"name":"francs","age":"31"}' :: jsonb || '{"sex":"male"}' :: jsonb;

{"age": "31", "sex": "male", "name": "francs"}

jsonb 鍵 /值的刪除有兩種方法,一種是通過操作符
“-”刪除,另一種通過操作符“#_”刪除指定鍵/值

第一種

SELECT '{"name" : "James", "email": "james@localhost"}':: jsonb - 'email';
{"name": "James"}

select '["red","green","blue"]'::jsonb - 0;
["green", "blue"]

第二種 操作符“#_”刪除指定鍵/值,通常用於有嵌套 json 數據刪除的場

  • 刪除嵌套contact中的fax 鍵值
SELECT
'{"name":"James","contant":{"phone":"01234567890", "fax":"01923 342234"}}' :: jsonb 
#-
'{contant,fax}' :: TEXT []

結果:
{"name": "James", "contant": {"phone": "01234567890"}}
  • 刪除嵌套contant中,坐標為0的鍵值
SELECT
'{"name":"James","contant":["first", "second", "third"]}' :: jsonb 
#-
'{contant,0}' :: TEXT []

結果: 
{"name": "James", "contant": ["second", "third"]}

鍵/值的更新也有兩種方式

  • 第一種方式為“||”操作符,“||”操作符可以連接 json鍵,也可以覆蓋重復的鍵值
select '{"name":"AganRun", "age":"31"}'::jsonb || '{"age":"100"}' :: jsonb;

{"age": "100", "name": "AganRun"}
  • 第二種方式是通過jsonb_set函數
    jsonb_set(target jsonb, path text[], new_value jsonb[, create_missing boolean])

target 指源jsonb數據, path指路徑, new_value 指更新后的鍵值, creat_missing 值為
true 表示如果鍵不存在則添加, create_missing 值為 false 表示如果鍵不存在則不添加

SELECT jsonb_set ('{"name":"francs","age":"31"}':: jsonb ,'{age}','"32"'::jsonb, false);

{"age": "32", "name": "francs"}

SELECT jsonb_set  ('{"name":"francs","age":"31"}':: jsonb ,'{sex }','"male"':: jsonb, true);

{"age": "31", "sex": "male", "name": "francs"}

數據類型轉換

格式化函數、CAST函數、操作符

3.9.1 通過格式化函數進行轉換

格式化函數

3.9.2 通過 CAST 函數進行轉換

varchar 字符類型轉換成 text 類型

select cast(varchar'123' as test);
 
123

varchar 字符類型轉換成 int4 類型

select cast(varchar'123' as text);

123

3.9.3 通過::操作符進行轉換

例子轉換成 int4 或 numeric 類型

select 1::int4, 3/2::numeric;

1 , 1.5

三種數據類型轉換方法,第-種方法兼容性相對較好,第三種方法用法簡捷


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM