毛毛Python進階之路6——MySQL 資料庫(二)
阿新 • • 發佈:2018-12-14
毛毛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!