关于数据库的操作
1.查看数据库的方式
show databases;
2.创建一个数据库
create database 数据库名
3.查看当前所在数据库
show tables;
4.删除数据库
drop database 数据库名;
5.创建表
create table 表名(不存在的表名才可以创建成功)(
字段名 字段类型 【属性】【索引】【注释】,
字段名 字段类型 【属性】【索引】【注释】,
......
字段名 字段类型 【属性】【索引】【注释】
)【表类型】【表字符集】
6.查看表结构
desc 表名
7.查看创建表的执行的命令
show create table 表名;
8.删除表
drop table 表名;
9.修改表名称
alter table 表名 rename 新表名;
10.修改表中的字段类型
alter table 表名 modify 修改名 类型;
12.修改表中的字段类型和字段名称
alter table 表名 change 源字段名 新字段 新类型;
13.在表中添加字段
alter table 表名 add 字段名 字段类型;
14.在表中指定位置添加字段
alter table 表名 add 字段名 字段类型 first;
alter table 表名 add 字段 字段类型 after 指定字段;
15.删除表中字段
语法:alter table 表名 drop 字段名;
16.使用指定数据库
use 数据库名;
关于表的操作
1.插入记录
语法:insert into 表名 values(字段值1,字段值2);
2.插入记录2
语法:insert into 表命(字段1,字段2)values(字段值1,字段值2);
3.查询表中记录
语法:select * from 表名;
4.查看指定字段记录
语法:select 字段 from 表名;
5.查看其他数据库的表
语法:select 字段 from 数据库名.表名;
6.删除表中记录
语法: delete from 表名 where 字段=字段值;
7.修改记录
语法:update 表名 set 要修改的字段名 where 字段号;
多表联查
1.内连接
根据表中共有的字段进行匹配,将表中符合条件的记录进行连接。
语法: select 字段 from a表 inner join b表2 on a表.字段=b表.字段;
2.外连接 (分为左外连接,右外连接)
左连接: select 字段 from a表 left join b表 on 条件; a主表显示指定字段内容,b从表
右连接: select 字段 from a 表 right join b 表 on 条件; a是从表;b是主表,都显示。
查询两个集合并集
union
1.数据类型不同可以进行合并 2.两个集合的列数要一致 3.表头是第一个集合的信息 4.union会去除重复
select Sname,Ssex from student
union
select Tname,Tsex from teacher
子查询 在查询中又有一个查询
所有子查询都需要小括号括起来
-- 查询id最大的学生
select * from student order by student.Sid desc limit 1
where 子查询
select * from student where Sid=(select max(Sid) from student)
from 子查询
select * from class
select count(Sid) from student group by classid
select * from class
left join (select classid,count(Sid) 人数 from student group by classid) t
on class.classid=t.classid
where 人数 > 3
exists 子查询 字句有数据 父句执行 字句没有数据 父句不执行
如果学生表中有男同学则查询出所有的老师
select * from teacher where exists (select * from student where Ssex = '男')
any some 子查询
Select …from…where a>any/some(…);
相当于
Select …from…where a>r1 or a>r2….a>rn
all子查询
Select …from…where a>all(…);
相当于
Select …from…where a>r1 and a>r2… and a>rn