舉例簡單介紹PostgreSQL中的數組,簡單介紹postgresql

來源:互聯網
上載者:User

舉例簡單介紹PostgreSQL中的數組,簡單介紹postgresql

 PostgreSQL 有很多豐富的開箱即用的資料類型,從標準的數字資料類型、到幾何類型,甚至網路資料類型等等。雖然很多人會忽略這些資料類 型,但卻是我最喜歡的特性之一。而數組資料類型正如你所期望的,可以在 PostgreSQL 儲存數組資料,有了這個特性,你可以在單個表中實現以往需要多個表才能實現的儲存要求。

為什麼要使用數組來儲存資料,如果你是應用開發人員,那麼在資料庫中使用同樣的模型來儲存程式中的資料,何樂而不為呢。況且這樣的做法還能提升效能。下面我們將介紹如何使用 PostgreSQL 的數群組類型。


假設你在一個網站上購買物品,那麼你所購買的資訊就可以用下面這個表來表示:
 

CREATE TABLE purchases (  id integer NOT NULL,  user_id integer,  items decimal(10,2) [100][1],  occurred_at timestamp);

在這個表中,擁有一個數組欄位來保持多個商品記錄,包括:

  •     購買商品的編號
  •     數量
  •     價格

要往這個表裡插入資料的 SQL 如下:
 
INSERT INTO purchases VALUES (1, 37, '{{15.0, 1.0, 25.0}, {15.0, 1.0, 25.0}}', now());
INSERT INTO purchases VALUES (2, 2, '{{11.0, 1.0, 4.99}}', now());
一個更有實際意義的例子是標籤的使用,你可以用標籤來標識購買的物品:

 

CREATE TABLE products (  id integer NOT NULL,  title character varying(255),  description text,  tags text[],  price numeric(10,2));

你可使用基本的查詢語句來擷取資料:

 

SELECT title, unnest(tags) items FROM products


你還可以使用 Postgres 的 Gin and Gist  索引來根據指定的標籤快速搜尋產品:
 

-- Search where product contains tag ids 1 AND 2SELECT *FROM  productsWHERE  tags @> ARRAY[1, 2] -- Search where product contains tag ids 1 OR 2SELECT *FROM  productsWHERE  tags && ARRAY[1, 2]

相關文章

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.