PostgreSQL 数据库入门
基础查询
-- 查询全部记录
select * from users;
-- 只查特定列
select name, city from users;
-- 条件筛选
select * from products where price > 100;
-- 排序 + 分页
select * from orders order by created_at desc limit 5;条件查询
-- 比较运算符:>, <, =, >=, <=, <>
select * from products where price > 200;
-- 逻辑组合:and / or
select * from users where city = '上海' and name = '张三';
select * from orders where status = 'pending' or status = 'cancelled';
-- 范围查询:between
select * from products where price between 50 and 300;
-- 模糊匹配:like(% 任意字符)
select * from products where name like '%手机%';
-- 注意:like 区分大小写,ILIKE 不区分聚合统计
-- count 统计记录数
select count(*) from users;
-- sum 求和
select sum(total_amount) from orders;
-- avg 平均值
select avg(price) from products;
-- max / min 最大值 / 最小值
select max(price), min(price) from products;
-- group by 分组统计
select city, count(*) from users group by city;分组筛选与排序
-- group by + having(筛选分组后的结果)
select status, count(*)
from orders
group by status
having count(*) > 2;
-- group by + order by(按聚合结果排序)
select status, count(*)
from orders
group by status
order by count(*) desc;
-- where + group by + having 联合使用
select user_id, count(*)
from orders
where status = 'paid'
group by user_id
having count(*) >= 1;多表关联查询
-- inner join:只返回匹配的记录
select u.name, o.id, o.total_amount
from users u
inner join orders o on u.id = o.user_id;
-- left join:返回左表全部记录
select u.name, count(o.id)
from users u
left join orders o on u.id = o.user_id
group by u.name;
-- 统计每个用户的订单总额(无订单则显示 0)
select u.name, coalesce(sum(o.total_amount), 0)
from users u
left join orders o on u.id = o.user_id
group by u.name;实用查询示例
-- 哪些用户下过单(去重)
select distinct u.name
from users u
inner join orders o on u.id = o.user_id;
-- 哪些用户从未下过单
select u.name
from users u
left join orders o on u.id = o.user_id
where o.id is null;关键概念速记
| 概念 | 说明 |
|---|---|
| 数据库 | 存储和管理数据的系统 |
| SQL | 结构化查询语言,用于操作数据库 |
| PostgreSQL | 开源关系型数据库,支持 JSONB、窗口函数等 |
| JOIN | 将多张表按关联字段组合查询 |
| 聚合函数 | count / sum / avg / max / min,常配合 group by |
学习 SQL 建议先熟悉单表查询和条件过滤,再逐步掌握分组统计和多表关联。