常用 SQL、约束、联表查询、子查询

常用SQL + 约束 + 联表查询 + 子查询 超精简干货

一、常用基础 SQL

1. 增删改查

-- 查询
select 字段1,字段2 from 表名 where 条件;
-- 查所有
select * from 表名;

-- 插入
insert into 表名(字段1,字段2) values(值1,值2);

-- 修改
update 表名 set 字段=值 where 条件;

-- 删除
delete from 表名 where 条件;

2. 常用关键字

  • where 条件过滤
  • order by 排序 asc升序 / desc降序
  • limit 分页 limit 起始下标,条数
  • distinct 去重
  • group by 分组
  • 聚合函数:count()总数、sum()求和、avg()平均、max()最大、min()最小

二、数据库常用约束

作用:保证数据合法、完整、不重复

  1. 主键约束 primary key
    唯一且非空,一张表只能一个主键
  2. 非空约束 not null
    字段不能为空
  3. 唯一约束 unique
    值不能重复,可以为空
  4. 默认约束 default
    不给值时使用默认值
  5. 外键约束 foreign key
    两张表建立关联,保证关联数据一致性
  6. 检查约束 check
    限制字段取值范围(如年龄>0)

三、联表查询(多表查询)

1. 内连接 inner join

只查两张表匹配到的数据

select * 
from 表1
inner join 表2 
on 表1.关联字段 = 表2.关联字段;

2. 左连接 left join

左表为准,左表全部显示,右表匹配不到显示null

select * 
from 表1
left join 表2 
on 表1.关联字段 = 表2.关联字段;

3. 右连接 right join

右表为准,右表全部显示,左表匹配不到显示null

4. 笛卡尔积(少用)

直接逗号分隔,不加 on 条件,会产生大量冗余数据


四、子查询

一条SQL查询结果,当作另一条SQL的条件/表

1. 单行子查询(= > < >= <=)

select * from user 
where age = (select age from user where name='张三');

2. 多行子查询 in / any / all

-- 查询出多个结果,用in匹配
select * from user 
where id in (select id from user where age>18);

3. 表级子查询(当作临时表)

select * from (select name,age from user) as temp;
posted @ 2026-05-07 15:34  张山山  阅读(10)  评论(0)    收藏  举报