postgresql 數群組類型初步實踐

來源:互聯網
上載者:User

標籤:


實踐環境

資料庫:postgresql 9.4;作業系統:windows

建立包含數群組類型的資料庫

注意在設定default 值時(當然你可以不指定預設值),要聲明數組的類型,像這樣聲明"::bigint[]"。

create table testarray(id serial primary key,images bigint[] default array[]::bigint[]);
插入數組值

注意插入數組時,也要聲明數組的類型,同上

insert into testarray (images) values(array[1,2,3,4,5,6]::bigint[]);
查詢剛插入的資料

查詢語句:

select * from testarray;

結果:

數組的操作 判斷元素是否存在(操作符:"any")

要注意為查詢出來的數組指定類型。

select 0 = any ((select images from testarray where id=1)::int[]) as isContain

查詢結果:

刪除元素(array_romeve),但不影響持久資料
select array_remove((select images from testarray)::varchar[],‘1‘);

查詢結果:

刪除元素,儲存結果

思路是將資料查詢出來進行操作之後("||"是一個數組操作符,合并元素和數組),再儲存回到資料庫。可以刪除單個元素,也可以刪除一個元素集(另一個數組),舉一反三。

update testarray set images = (select images from testarray where id=1)::int[] || 1; 
select images from testarray;

結果:

給資料添加元素(操作符:"||"),但是不儲存

給數組添加元素實際上就是將元素合并到一個數組裡,辦法很多,這裡只距離"||"操作符的使用。

單個元素添加到數組
select (select images from testarray where id=1)::int[] || 100 as newimages;

結果:

添加多個元素到數組
select (select images from testarray where id=1)::int[] || array[200,300,300,400]::int[] as newimages;

結果:

給資料添加元素,並且儲存

思路同5.3

update testarray update set images = (select images from testarray where id=1)::int[] || array[200,300,300,400]::int[] ;
select images from testarray;

結果:

附錄

本部落格不是系統的教程,只是簡單的介紹postgresql 資料類型的使用。關於postgresql數群組類型的操作符和函數,可以參見官方文檔:http://www.postgresql.org/docs/9.1/static/functions-array.html

postgresql 數群組類型初步實踐

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.