一、数据库的约束
约束类型 | 说明 | 示例 |
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 ='女') |
二、表的关系
1.一对一
2.一对多
3.多对多:需要创建中间表来映射两张表的关系
三、语法进阶:
1、新增
INSERT INTO table_name [(column [, column ...])] SELECT ...
2、子查询(嵌套查询):嵌套在其他SQL语句中的select语句
1.单行子查询:返回一行记录的子查询
多行子查询:返回多行记录的子查询
2.in/not in
-- 使用 IN
select * from score where course_id in (select id from course where
name!='语文' or name!='英文');
-- 使用 NOT IN
select * from score where course_id not in (select id from course where
name!='语文' and name!='英文');
//多列包含
-- 插入重复的分数:score, student_id, course_id列重复
insert into score(score, student_id, course_id) values
-- 黑旋风李逵
(70.5, 1, 1),(98.5, 1, 3),
-- 菩提老祖
(60, 2, 1);
-- 查询重复的分数
SELECT
*
FROM
score
WHERE
( score, student_id, course_id ) IN ( SELECT score, student_id,
course_id FROM score GROUP BY score, student_id,course_id
having count(0)>1);
3.exists/not exists
select *from score sco where exists(select*from course cou where(name='语文' or name='英文')and cou.id=sco.course_id);
select *from score sco where not exists(select*from course cou where(name!='语文' and name!='英文')and cou.id=sco.course_id);
3、合并查询
在实际应用中,为了合并多个select的执行结果,可以使用集合操作符 union,union all。使用UNION和UNION ALL时,前后查询的结果集中,字段需要一致。
union ——该操作取两个结果集的并集,自动去除相同行记录,显示筛选后的结果集
union all——取两个结果集的并集,显示全部结果,未筛选
-- UNION:去除重复数据
select ... from ... where 条件
union
select ... from ... where 条件
-- UNION ALL:不去重
select ... from ... where 条件
union all
select ... from ... where 条件
-- 使用UNION和UNION ALL时,前后查询的结果集中,字段要一致
性能比较:
性能效率最优:exists
查询的语法进阶总结
1. 聚合函数:MAX、MIN、AVG、COUNT、SUM
2. 分组查询:GROUP BY... HAVING...
3. 内连接:select ... from 表1,表2 where 条件
-- inner可以缺省
select ... from 表1 join 表2 on 条件 where 其他条件
4. 外连接:select ... from 表1 left/right join 表2 on 条件 where 其他条件
5. 自连接:select ... from 表1 ,表1 where 条件
select ... from 表1 join 表1 on 条件
6. 子查询:
```sql
-- 单行子查询
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 条件
7.合并查询
-- UNION:去除重复数据
select ... from ... where 条件
union
select ... from ... where 条件
-- UNION ALL:不去重
select ... from ... where 条件
union all
select ... from ... where 条件
-- 使用UNION和UNION ALL时,前后查询的结果集中,字段要一致