01.增删改查命令
1.1 最基本查询语句
1 | mysql> select * from student limit 2; #仅查看student表中前两行数据 |
1.2 where; like; order by
1 | mysql> select * from student where id >3 and age >103; |
1.3 GROUP BY
- 指定以什么分组(比如可以统计出有多少同名数据)
1 | mysql> select name,count(*) from student group by name; |
1.4 修改(update)
1 | mysql> update student set name="lisi",age=22 where id=1; #将表中id=1的条目改成name=lisi,age=22 |
1.5 删除(delete)
1 | mysql> delete from student where name="zhangsan"; #删除student表中所有name=“zhangsan” |
02.一对多
2.1 学生表&上课记录
1 | #1、student表 |
2.2 在student表中创建记录
- 在student表中创建两条记录
1 | mysql> insert into student(name,age,register_data) values("zhangsan",100,"2016-06-20"); |
2.3 student_record表添加关联
- 在student_record表中创建与student表的关联记录(day,status,stu_id)
1 | mysql> insert into study_record (day,status,stu_id) values(1,"yes",1); # student表id=1第一天到了 |
2.4 关联数据不能删除
- 如果有student表中有student_record表关联的数据,你是不能删除student表中的记录(报错)
1 | mysql> delete from student where name='lisi'; |
2.5 查看创建记录
- 查看刚刚创建study_record表结构创建记录
1 | mysql> show create table study_record; |
2.6 left join(左连接
)
左连接:两个表的差集(左表有就显示)
- 1、左连接where只影向右表,所以左表(student)中数据全部显示,右表study_record表中不符合where条件的数据不会显示
1 | mysql> select name,day,status from student left join study_record on student.id=study_record.stu_id; |
2.7 right join(右连接
)
-
右连接:两个表的差集(右表有才显示)
-
1、右连接where只影向左表,所以左表(student)中不符合where条件的数据不会显示,右表study_record表内容全部显示
-
select * from student right join study_record on student.id=study_record.stu_id;
1
2
3
4
5
6
7
8
9
10
11
12
<img src="https://raw.githubusercontent.com/DYL521/DYL521.github.io/image-save/doc_image/mysql/image-20210224141150316.png" style="width: 900px; margin-left: 0px;"> </img>
### 2.8 inner join(`内连接`)
- 内连接:两个表的交集
- inner join:理解为“有效连接”,`两张表中都有的数据才会显示left join`
```python
select * from student inner join study_record on student.id=study_record.stu_id; # 等价于面这条语句
select * from student,study_record where study_record.stu_id = student.id;
2.9 full join(全连接
)
1 | select * from a FULL JOIN b on a.a = b.b; # MySQL不支持这个命令(可以使用下面语句代替,两行是一个语句) |
__END__