1. 数据库约束
约束类型 | 说明 | 示例 |
---|---|---|
NULL约束 | 使用NOT NULL指定列不为空 | name varchar(20) not null, |
UNIQUE唯一约束 | 指定列为唯一的、不重复的 | name varchar(20) unique, |
DEFAULT默认值约束 | 指定列为空时的默认值 | age int default 20, |
主键约束 | NOT NULL 和 UNIQUE 的结合 | id int primary key, |
外键约束 | 关联其他表的主键或唯一键 | foreign key (字段名) references 主表(列) |
CHECK约束(了解) | 保证列中的值符合指定的件 | check (sex =‘男’ or sex=‘女’) |
2. 标的关系
- 一对一
- 一对多
- 多对多: 一般需要创建中间表来映射两张表的关系
3. 新增
insert into [表名] [行] from [];
4. 查询
- 聚合函数:MAX、MIN、AVG、COUNT、SUM
- 分组查询:GROUP BY… HAVING …
- 内连接:
select ... from 表1,表2 where 条件
-- inner可以缺省
select ... from 表1 join 表2 on 条件 where 其他条件
- 外连接:
select ... from 表1 left/right join 表2 on 条件 where 其他条件
- 自连接:
select ... from 表1,表1 where 条件
select ... from 表1 join 表1 on 条件
- 子查询:
-- 单行子查询
select ... from 表1 where 字段1 = (select ... from ...);
-- [NOT] IN
select ... from 表1 where 字段1 in (select ... from ...);
-- [NOT] EXISTS
select ... from 表1 where exists (select ... from ... where 条件);
-- 临时表:form子句中的子查询
select ... from 表1, (select ... from ...) as tmp where 条件
- 合并查询:
-- UNION:去除重复数据
select ... from ... where 条件
union
select ... from ... where 条件
-- UNION ALL:不去重
select ... from ... where 条件
union all
select ... from ... where 条件
-- 使用UNION和UNION ALL时,前后查询的结果集中,字段需要一致
注意:
SQL查询中各个关键字的执行先后顺序: from > on> join > where > group by > with > having >select >distinct > order by > limit