版权声明:全是自学! https://blog.csdn.net/qq_42874244/article/details/83934589
毛毛Python进阶之路6——MySQL 数据库(二)
一、对于自增
show create table 表名; # 查看表是怎样创建的。
show create table 表名\G; #将某个表旋转90度
alter table 表名 AUTO_INCREMENT=10; #修改自增数列起始值
truncate table <表名>; # 如果列表有自增就去掉自增
二、唯一索引
creat table t1(
id int auto_increment primany key,
num int,
unique <唯一索引名称>(列名,列名), #联合唯一索引
constraint <外键索引>
)engine=innodb auto_increment (设置步长) default charset=utf8;
唯一索引——>可以加速查找
约束不能重复(可以为空)
三、SQL语句数据行操作补充
以下操作基于表【tb11,tb12】
1、增、删、改、查
增
1. insert into tb11(name,age) values(‘alex’,12);
2. insert into tb11(name,age) values('alex',12),('egon',12);
3. insert into tb11(name,age) select name,age from tb12; #可以从一个表直接导入另一个表
删
4. delect from tb12;
5. delect from tb12 where id <条件>;
对于条件可以是 > < = and or.....
改
6. update tb12 set name='alex' where id > 12 and name='XX';
7. update tb12 set name='alex',age=19 where id>12 and name='XX';
查
8. select * from tb12;
9. select id,name from tb12;
10. select id name from tb12 where id>10 or name='alex';
11. select id,name as cname from tb12 where <条件>;
12. select name,age,11 from tb12; ==>select * from tb12 <条件>;
四、表内其他操作
1、通配符
通配符的出现时为了在表中实现模糊匹配,模糊查找。
select * from tb12 where name like "a%"; #可以匹配名字里面以 a 开头的数据
select * from tb12 where anme like a_"; #可以匹配名字里面 以 a 开头的两位数据 如ab ac ad
2、分页
有时候数据有点多,我们不能直接全部显示,所以可以部分取出来显示,用以达到分页的目的。
select * from tb12 limit 10; #查看前十位数据
select * from tb12 limint A,B # 查看第A个数据开始的后B位数据,如(30.10)表示第30个数据的后十个数据
select * from tb12 limit 10 offset 20; # 从第20行数据开始读取,读取第10行。
3、排序
数据一般都是按照主键顺序排的我们可以改变排序方式
desc 从大到小排序
asc 从小到大排序
select * from tb12 order by id desc;
select * from tb12 order by id asc;
select * from tb12 order by age desc,id desc; # 先让age从大到小排序,age里面有重复的 再从重复数据里面让ID从大到小排序
4.分组
有时候筛选出来的数据有重复项,比如说课程,所以此时就需要去重然后分组!
select count(id),max(id),part_id from userinfo group by part_id;
# 这里是对part_id进行分组,其中富足的时候可以用相应的函数对数据进行整合如:count,max,min,sum,avg……
注意:如果对聚合函数(一次筛选后的数据)进行二次筛选时必须使用having函数,不能用where函数!
select count(id),part_id from userinfo group by part_id having count(id)>1;
5、连表操作
当建立多个数据库和多个外键的时候此时就需要对出具进行处理将两个或者多个表格进行联合:
1. select * from userinfo,department;
2. select * from userinfo,department where userinfo.part_id=department.id;
3. select * from userinfo left join department on userinfo.part_id=department.id #将表格连接在左,建议用这个方法!
# 链接两个以上的表格:
select * from
score
left join userinfo on score.part_id=userinfo.id,
left join userinfo1 on score.paret_id1=userinfo1.id;
6、临时表的创建
select num,course_id from (select num,course_id from score where num>60) as B;
# 此时将select num,course_id from score where num>60表重命名为表B 进行操作
MySQL的学习非常重要的,而且有一些涉及到表格的特别难的操作,但是万变不离其宗,只要将基本数据库操作记忆准确,再加上合理的逻辑推理是可以成功过关的!
下面有一些练习题和答案:
练习题: http://www.cnblogs.com/wupeiqi/articles/572994.html(题目来自老男孩教育!)
答案:http://www.cnblogs.com/wupeiqi/articles/574896.html(答案来自老男孩教育!)
人生苦短,我学python!