更新时间:2026-10-16 GMT+08:00
单表查询
操作场景
本节通过一个商品库存表的示例,介绍单表查询的基本用法,包括简单查询、条件筛选、排序、限制结果数量和聚合查询。
示例表说明
本章使用商品库存表newproducts作为示例,表结构如下:
| 字段名 | 类型 | 说明 |
|---|---|---|
| product_id | INTEGER | 商品编号 |
| product_name | VARCHAR2(60) | 商品名称 |
| category | VARCHAR2(60) | 商品类别 |
| quantity | INTEGER | 库存数量 |
创建示例表并插入数据
执行以下语句创建示例表并插入数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | CREATE TABLE newproducts ( product_id INTEGER, product_name VARCHAR2(60), category VARCHAR2(60), quantity INTEGER ) STORE AS orc; INSERT INTO newproducts VALUES (1502, 'earphones', 'electronics',150); INSERT INTO newproducts VALUES (1601, 'telescope', 'toys',80); INSERT INTO newproducts VALUES (1666, 'Frisbee', 'toys',244); INSERT INTO newproducts VALUES (1700, 'interface', 'books',100); INSERT INTO newproducts VALUES (2344, 'milklotion', 'skin care',320); INSERT INTO newproducts VALUES (3577, 'dumbbell', 'sports',550); INSERT INTO newproducts VALUES (1210, 'necklace', 'jewels', 200); |
简单查询
通过SELECT ... FROM ... 语句从数据库中获取结果。
1 2 3 4 5 6 7 8 9 10 11 | SELECT category FROM newproducts; category ------------ electronics toys sports jewels books skin care toys (7 rows) |
对结果进行筛选
通过WHERE语句对查询的结果进行过滤,找到想要查询的部分。
1 2 3 4 5 6 | SELECT * FROM newproducts WHERE category='toys'; product_id | product_name | category | quantity ------------+--------------+----------+---------- 1601 | telescope | toys | 80 1666 | Frisbee | toys | 244 (2 rows) |
对结果进行排序
使用ORDER BY语句可以让查询结果按照期望的方式进行排序。
1 2 3 4 5 6 7 8 9 10 11 | SELECT product_id,product_name,category,quantity FROM newproducts ORDER BY quantity DESC; product_id | product_name | category | quantity ------------+--------------+-------------+---------- 3577 | dumbbell | sports | 550 2344 | milklotion | skin care | 320 1666 | Frisbee | toys | 244 1210 | necklace | jewels | 200 1502 | earphones | electronics | 150 1700 | interface | books | 100 1601 | telescope | toys | 80 (7 rows) |
限制结果查询数量
如果只需要查询返回部分结果,可使用LIMIT语句限制返回记录数
1 2 3 4 5 6 7 8 9 | SELECT product_id,product_name,category,quantity FROM newproducts ORDER BY quantity DESC limit 5; product_id | product_name | category | quantity ------------+--------------+-------------+---------- 3577 | dumbbell | sports | 550 2344 | milklotion | skin care | 320 1666 | Frisbee | toys | 244 1210 | necklace | jewels | 200 1502 | earphones | electronics | 150 (5 rows) |
聚合查询
可以通过使用GROUP BY语句配合聚合函数,构建一个聚合查询来关注数据的整体情况。
1 2 3 4 5 6 7 8 9 10 | SELECT category, string_agg(quantity,',') FROM newproducts GROUP BY category; category | string_agg -------------+------------ books | 100 electronics | 150 skin care | 320 jewels | 200 toys | 80,244 sports | 550 (6 rows) |
父主题: 表查询示例