NormanZyq
发布于 2019-07-21 / 305 阅读
0
0

Mysql基础

外键设置

create table student_table(
  student_id varchar(10) primary key,
  student_name varchar(20) not null,
  student_birthday date,
  class_id int(4),
  
  # set foreign key, using constraint keyword
  constraint foreign key (class_id) references class_table(class_id)
                          on delete set null # 删除class时,学生表的班级被设为null
);

插入

insert into student_table (student_id, student_name, student_birthday, class_id)
values ('1173710121', 'Bob', '19990101', 1);

如果是按照顺序设置所有列的数据,就不需要在table名后面加括号

更新

update student_table
set student_birthday = '19710101'
where student_id = '1173710121'

查询

查询语句先解析from,再解析select

select *
from student_table where student_id='1173710121';

分组查询:

# 聚合函数 count max min avg sum

select count(*), class_id # 只有聚合函数能往select里面加,不然是没有意义的
from student_table
group by class_id;
# 这之后还能继续orber by

查询结果:

`count(*)`class_id
122
213

多表查询:

# 多表查询
# 1. 学生名、学号、班级名:学生表+班级表
select s.student_name, s.student_id, c.class_name
from student_table s,
     class_table c # s和c是表别名
where s.class_id = c.class_id

# 2. 查询学生信息,条件是:班级名是Java 1班
select s.*
from student_table s,
     class_table c
where c.class_name = 'Java 1班'
  and s.class_id = c.class_id

多表查询也可以结合之前的分组查询等技术


评论