使用 ARRAY

在 PostgreSQL 中使用函数处理数据

Brian Piccolo

Sr. Director, Digital Strategy

开始之前

CREATE TABLE 示例

CREATE TABLE my_first_table (
    first_column text,
    second_column integer
);

INSERT 示例

INSERT INTO my_first_table 
    (first_column, second_column) VALUES ('text value', 12);
在 PostgreSQL 中使用函数处理数据

ARRAY:一种特殊类型

让我们创建一个包含两个数组列的简单表。

CREATE TABLE grades (
    student_id int,
    email text[][],
    test_scores int[]
);
在 PostgreSQL 中使用函数处理数据

带 ARRAY 的 INSERT 语句

示例 INSERT 语句:

INSERT INTO grades 
    VALUES (1, 
    '{{"work","[email protected]"},{"other","[email protected]"}}', 
    '{92,85,96,88}' );
在 PostgreSQL 中使用函数处理数据

访问 ARRAY

SELECT
   email[1][1] AS type,
   email[1][2] AS address,
   test_scores[1],
FROM grades;
+--------+--------------------+-------------+
| type   |  address           | test_scores |
|--------|--------------------|-------------|
| work   | [email protected] | 92          |
| work   | [email protected] | 76          |
+--------+--------------------+-------------+

注意:PostgreSQL 的数组下标从 1 开始,而非 0。

在 PostgreSQL 中使用函数处理数据

搜索 ARRAY

SELECT
   email[1][1] as type,
   email[1][2] as address,
   test_scores[1]
FROM grades
WHERE email[1][1] = 'work';
+--------+--------------------+-------------+
| type   |  address           | test_scores |
|--------|--------------------|-------------|
| work   | [email protected] | 92          |
| work   | [email protected] | 76          |
+--------+--------------------+-------------+
在 PostgreSQL 中使用函数处理数据

ARRAY 的函数与运算符

SELECT
   email[2][1] as type,
   email[2][2] as address,
   test_scores[1]
FROM grades
WHERE 'other' = ANY (email);
+---------+---------------------+-------------+
| type    |  address            | test_scores |
|---------|-----------------------------------|
| other   | [email protected] | 92          |
| null    | null                | 76          |
+---------+---------------------+-------------+
在 PostgreSQL 中使用函数处理数据

ARRAY 的函数与运算符

SELECT
   email[2][1] as type,
   email[2][2] as address,
   test_scores[1]
FROM grades
WHERE email @> ARRAY['other'];
+---------+---------------------+-------------+
| type    |  address            | test_scores |
|---------|-----------------------------------|
| other   | [email protected] | 92          |
| null    | null                | 76          |
+---------+---------------------+-------------+
在 PostgreSQL 中使用函数处理数据

Passons à la pratique !

在 PostgreSQL 中使用函数处理数据

Preparing Video For Download...