DDL库/表结构(建库,建表,改字段,删表)
# 创建数据库
create database test_db
# 建表
create table user(
id serial primary key,
name varchar(32) not null,
age int null
)
# 修改表字段
alter table user add column email varchar(50) # 新增字段
alter table user drop column email # 删除字段
alter table user alter column name type varchar(50) # 修改字段类型
# 删除表
drop table user
DML增删查改
# 新增 insert
insert into user (name,age) values ('张三',22)
insert into user (name,age) values ('张三',22),('李四',22)
# 修改 update
update user set age=23 where id=1
update user set age=23 where id in (1,2,3)
# 删除 delete
delete from user where id=1
truncate table user # 清空全表
# 查询 select
select * from user # 全查
select id,name from user # 指定字段
select * from user where id=1 # 等于
select * from user where age between 20 and 30 # 区间 between and
select * from user where id in (1,2,3) # in多选
select * from user where age is null # 空
select * from user where age is not null # 非空
select * from user where age>20 and age<40
select * from user where age=20 or age=40
# 模糊匹配 like 区分大小写
select * from user where name like '张%'
select * from user where name like '%张%'
select * from user where name like '%张'
# 模糊匹配 ilike 不区分大小写
select * from user where name ilike '%zhang%'
# 排序 order by
select * from user order by age asc # 升序
select * from user order by age desc # 降序
# 分页 limit offset
select * from user limit 3 offset 0 # 前3条
select * from user limit 3 offset 4 # 第 5~7 条
联表查询
# 内连接 inner join
select user.id,user.name,todos.title,todos.is_finish from user inner join todos on user.id = todos.id
# 左连接 left join
select user.id,user.name,todos.title,todos.is_finish from user left join todos on user.id = todos.id
聚合+分组
# 聚合:总数量,平均年龄,最大最小
select count(*),avg(age),max(age),min(age) from user
# 分组后过滤
select user.name,count(id) todo_num
from user
left join todo on user.id = todo.user_id
group by user.id,user.name
having count(todo.id) > 2
子查询
select * from user where id in (select user_id from todo where is_finnish=true)
CASE WHEN
select name,age,case
when age < 25 then '青年'
when age >=25 and age <35 then '壮年'
else '中年'
end as age_type
from user
日期相关SQL
select * from user where extract(year from create_time)=2025; # 查询2025年创建的用户
select * from user where extract(month from create_time)=3; # 某月的数据
其他
# 字符串拼接
select concat(name,'-',age) from user
# 去重
select distinct name from user