数据库的基本操作
查询数据库:show databases;
连接数据库:use 数据库名;
新建(删除)数据库:cteate(drop) database 数据库名
表的基本操作
查询表:show tables;
新建(删除)表:create(drop)table 表名
增删改查——“增”
增加列:alter table 表名 add 列名 类型 约束
向表中插入数据:insert into 表名 列名 values 数据
增删改查——“删”
删除列:delete table 表名 drop 列名 类型 约束
删除行:delete from 表名 where 条件
增删改查——“改”
修改表:Alter table 表名 change 列名 新列名 类型;
修改列名:Alter table 表名 change 列名 列名 新类型;
修改列类型:Alter table 表名 modify 列名 新类型;
增删改查——“查”
基本查询(like 表示模糊查询):select * from 表名 where/having like
内(左右)链接查询:select * from 表名 as 别名 inner(left / right)表名 as 别名 on 条件 where 条件
子查询【也可以加在条件里】:select * from (select * from 表名)
其他关键字
聚合函数
其他基本操作
建立索引
create index 索引名 on 表名 列名
删除索引:
法一:
drop index 索引名 on 表名
法二:
alter table 表名 drop index 索引名
练习
这里分别有三个表:students 、scores 、 courses
students表
scores 、 courses表
1、查询20岁以下 的学生
select * from students where age<20
2、查询年龄小于20的女同学
select * from students where age<20 and sex='女'
3、查询姓名中带有乔的学生
select * from students where name like '%乔'
4、查询年龄在18至20的学生
select * from students where age between 18 and 20
5、查询所有学生信息,按年龄从大到小排序,年龄相同时,再按学号从小到大排序
select * from students order by age desc,studentNo
6、查询前3行学生信息
select * from students limit 0,3
7、查询课程信息及课程的成绩
select * from courses cs,scores sc where cs.courseNo = sc.courseNo
select * from courses cs inner join scores sc on cs.courseNo = sc.courseNo
8、查询王昭君的数据库成绩,要求显示姓名、课程名、成绩
select
stu.name,
cs.name,
sc.score
from
students stu,
scores sc,
courses cs
where
stu.studentNo = sc.studentNo
and sc.courseNo = cs.courseNo
and stu.name = '王昭君'
and cs.name = '数据库'
---------------------------------------
select
stu.name,
cs.name,
sc.score
from
students stu
inner join scores sc on stu.studentNo = sc.studentNo
inner join courses cs on sc.courseNo = cs.courseNo
where
stu.name = '王昭君' and cs.name = '数据库'
9、查询所有课程的成绩,包括没有成绩的课程
select
*
from
scores sc
right join courses cs on cs.courseNo = sc.courseNo
left join students stu on stu.studentNo = sc.studentNo
10、查询王昭君的成绩,要求显示成绩(在成绩表(scores)中查询)
select * from scores where studentNo =
(select studentNo from students where name = '王昭君')