更新时间:2024-09-02 GMT+08:00
单表查询
示例表:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
CREATE TABLE newproducts ( product_id INTEGER NOT NULL, product_name VARCHAR2(60), category VARCHAR2(60), quantity INTEGER ) WITH (ORIENTATION = COLUMN) DISTRIBUTE BY HASH(product_id); 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 ------------ electr sports jewels toys 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 |
SELECT category, string_agg(quantity,',') FROM newproducts group by category; category | string_agg -------------+------------ toys | 80,244 books | 100 sports | 550 jewels | 200 skin care | 320 electronics | 150 |
父主题: 数据读取