基础 SELECT

本章将讨论如何使用简单的 SELECT 语句从 PostgreSQL 查询数据。PostgreSQL 的 SELECT 语句有诸多独特的特性,让我们一起感受一下。

本章将使用示例数据库中的 customer 作演示。连接到示例数据库,并执行 \dS customer; 可以查看该表的结构:

dvdrental=# \dS customer;
                                             Table "public.customer"
   Column    |            Type             | Collation | Nullable |                    Default                    
-------------+-----------------------------+-----------+----------+-----------------------------------------------
 customer_id | integer                     |           | not null | nextval('customer_customer_id_seq'::regclass)
 store_id    | smallint                    |           | not null | 
 first_name  | character varying(45)       |           | not null | 
 last_name   | character varying(45)       |           | not null | 
 email       | character varying(50)       |           |          | 
 address_id  | smallint                    |           | not null | 
 activebool  | boolean                     |           | not null | true
 create_date | date                        |           | not null | 'now'::text::date
 last_update | timestamp without time zone |           |          | now()
 active      | integer                     |           |          | 

基本查询

-- 查询单个字段
SELECT first_name FROM customer;

-- 查询多个字段
SELECT first_name, last_name FROM customer;

-- 查询所有字段
SELECT * FROM customer;

-- 表达式
SELECT 'AXUM中文网';

-- 运算符和表达式
SELECT first_name || ' ' || last_name, email FROM customer;
  • 通过 AS 指定别名,虽然用作别名时AS 通常可以省略,但加上它会更明确且易于理解
  • "":是 PostgreSQL 的定界符。当 SQL 语句中的对象名有特殊字符、关键字等情况时,需要使用定界符将其包裹。
-- 排序
SELECT first_name, last_name FROM customer ORDER BY first_name;

-- 排序(同上)
SELECT first_name, last_name FROM customer ORDER BY first_name ASC;

-- 复合排序
SELECT first_name, last_name FROM customer ORDER BY first_name ASC, last_name DESC;

-- 使用表达式的值进行排序
SELECT first_name, LENGTH(last_name) AS len FROM customer ORDER BY len DESC;
  • 使用 ORDER BY 子句进行排序,可选
    • ASC:默认,升序,从小到大
    • DESC:降序,从大到小
  • 可以有多个排序规则,当第一个排序规则出现冲突(多条记录的排序值相同)时,会使用后面的排序规则继续排序,以此类推。
  • 可以使用 SELECT 中的表达式的值进行排序
  • PostgreSQL 还提供了针对 NULL 的排序
-- 创建新表
CREATE TABLE sort_demo(
    -- 由于未加 NOT NULL 约束,num 字段将允许 NULL 值 
	num INT
);

-- 插入一些数据
INSERT INTO sort_demo(num)
VALUES(1),(2),(3),(null);

-- 按 num 升序
SELECT num FROM sort_demo ORDER BY num;
/* 结果
 num 
-----
   1
   2
   3
   [null] 
*/

-- 将 NULL 值 放在非NULL值后面
SELECT num FROM sort_demo ORDER BY num NULLS LAST;
/* 结果
 num 
-----
   1
   2
   3
   [null] 
*/

-- 将NULL值放在非NULL值前面
SELECT num FROM sort_demo ORDER BY num NULLS FIRST;
/* 结果
 num 
-----
   [null]
   1
   2
   3
*/

DISTINCT 子句

DISTINCT 子句用于去除 SELECT 中重复的数据。

  • PostgreSQL 提供了 DISTINC ON(表达式) ,用于保留每组重复项的“第一行”
    • 请配合 ORDER BY 使用。如未指定 ORDER BY ,PostgreSQL 的数据顺序是未定的(通常会按写记录(插入、修改)的前后排序)
    • 它的表达式 必须和 ORDER BY 第一个表达式匹配。比如上例中的 字段1
要查看完整内容,请先登录