PostgreSQL的數(shù)組
PostgreSQL 有很多豐富的開箱即用的數(shù)據(jù)類型,從標準的數(shù)字數(shù)據(jù)類型、到幾何類型,甚至網(wǎng)絡數(shù)據(jù)類型等等。雖然很多人會忽略這些數(shù)據(jù)類型,但卻是我最喜歡的特性之一。而數(shù)組數(shù)據(jù)類型正如你所期望的,可以在 PostgreSQL 存儲數(shù)組數(shù)據(jù),有了這個特性,你可以在單個表中實現(xiàn)以往需要多個表才能實現(xiàn)的存儲要求。
為什么要使用數(shù)組來存儲數(shù)據(jù),如果你是應用開發(fā)人員,那么在數(shù)據(jù)庫中使用同樣的模型來存儲程序中的數(shù)據(jù),何樂而不為呢。況且這樣的做法還能提升性能。下面我們將介紹如何使用 PostgreSQL 的數(shù)組類型。
假設你在一個網(wǎng)站上購買物品,那么你所購買的信息就可以用下面這個表來表示:
- CREATE TABLE purchases (
- id integer NOT NULL,
- user_id integer,
- items decimal(10,2) [100][1],
- occurred_at timestamp
- );
在這個表中,擁有一個數(shù)組字段來保持多個商品記錄,包括:
- 購買商品的編號
- 數(shù)量
- 價格
要往這個表里插入數(shù)據(jù)的 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)
- );
你可使用基本的查詢語句來獲取數(shù)據(jù):
- SELECT title, unnest(tags) items FROM products
你還可以使用 Postgres 的 Gin and Gist 索引來根據(jù)指定的標簽快速搜索產(chǎn)品:
- -- Search where product contains tag ids 1 AND 2
- SELECT *
- FROM products
- WHERE tags @> ARRAY[1, 2]
- -- Search where product contains tag ids 1 OR 2
- SELECT *
- FROM products
- WHERE tags && ARRAY[1, 2]
英文原文:http://craigkerstiens.com/2012/08/20/arrays-in-postgres/