Mysql初学者基本操作
mysql -uroot -p #账户
root #密码
show databases; #查看所有的库
create database 库名 charset utf8; #创建新库
use 库名; #进入某一库
show tables; #查看当前库下所有的表
create 表名1(id int not null ,name varchar(32),primary key(id)); #创建新表
create 表名2(id int not null ,namevarchar(32),primary key (id) 外键名_id int,foreign key(外键名_id)references 表一(id)); #创建新表2和外键约束
desc 表名; #查看某一张表的内容
alter table 表名 modify name(char(3));
alter table 表名 change name name1(char(2));#修改
drop table 表名; #删除表
操作表内
insert into 表名 valies(1,'egon1'),(2,'egon2').(3,'egon3'); #增
select * form 表名; #查
update 表名 set name=‘sb’ where id=2; #改
delete from 表名 where id=1; #删
delete from 表名; #清空表
truncate table 表名; #删除速度快 从零开始
#插入数据
1.全列插入
insert into 表名 values(...),(...);
2.部分插入
insert into 表名 (字段1,字段2,....)values(值1,值2,...);
#自增长约束
-主键是自动增长,但是在全列插入时需要占位,通常使用空值(0或null);
-字段默认值default 来占位,插入成功后以实际数据为准
insert into 表名 values (1,'lxx', default,1)
创建外键
create table students(id int primary key auto_increment,name varchar(20)default '',age int default 0,cls_id int )
查询
select * from 表名;(查全部)
select id,name,age from 表名;(查字段)
select id as 序号,name as 名字 from 表名;(查字段)
select id 序号 ,name 名字 from 表名;(查字段不带as)
select s.id 序号,s.name名字 from 表名 as s;(as起别名)
select distinct gender from students;(消除重复数据)
select * from students where 字段>值;
select * from students where 字段>值 or 字段2>值2;
select * from students where 字段>值 and 字段2<值2;
select * from students where 字段>=值 and 字段<=值2;
select * from students where 字段 between 值 and 值2;
select * from students where 字段 is null;
模糊查询
select * from students where name like '黄%';
select * from students where name like '__';
in的用法
select * from students where id in(1,2,5);
排序
select * from students order by age asc,height asc;
select * from students order by age desc;
查询并排序
select * from students where age>20 order by height desc;
分页
select * from students where age>=18 limit 3,3;
聚合函数
查询总数
select count(*)from students;
查询最大值
select max(字段)from students;
查询最小值
select min(字段)from students;
计算总数
select sum(字段)from students;
计算平均数
select avg(字段)from students;
select group_concat(name),gender from students group by gender;
子句执行顺序
从 哪里 分组 选择 去重 有 排序 限制
from > where > group by > select > distinct > having > order by > limit‘
子查询
select age from students where name='黄蓉';
select * from students where age>(select age from students where name='黄蓉');
内连接
1.内连接:将俩张表连接在一起,匹配的部分构建在虚拟表中,不相匹配的数据丢弃
2 语法:
select 字段 from 表1
inner join 表2
on 连接条件;
3.学生+班级 连接班级与学生表 连接条件为学生的班级id等于班级的id
内连接
select * from students
inner join classes
on students.cls_id=classes.id;
左连接
select * from students
left join classes
on students.cls_id=classes.id;
右连接
select * from students
right join classes
on students.cls_id=classes.id;