pymysql的增刪改查、索引
1.pymysql增刪改
一定要有commit()
2.pymysql查詢
fetchone()
fetchmany(size)
fetchall()
3.索引
作用:約束+加速查詢
普通索引:create index ix_name on 表名(欄位名);
作用:加速查詢
唯一索引:create unique index un_name on 表名(欄位名);
作用:約束+加速查詢
主鍵索引:設定主鍵
覆蓋索引:在索引檔案中直接獲取資料
例如:select name from big_data where name = "zhang50000"; 對name欄位設定了索引
索引合併:把多個單列索引一起使用
select * from big_data where name = "zhang13131" and id = 13131;
聯合索引:
聯合普通索引
聯合唯一索引
聯合主鍵索引
最左字首:
如果使用組合索引,name email 組合索引之後,查詢
1.name和email 使用索引
2.name 使用索引
3.email 不使用索引
對於同時搜尋n個條件時,組合索引的效能好於多個單列索引
組合索引的效能>索引合併的效能
對於索引:
1.建立索引:
注意事項:
1.避免使用select *
2.count(1)或count(列)代替count(*)
3.建立表時儘量使用char代替varchar
4.表的欄位順序固定長度的欄位優先
5.組合索引代替多個單列索引(經常使用多個條件查詢)
6.儘量使用短索引(create index ix_title on tb(title(16)));特殊的資料型別text
7.使用連線(join)代替子查詢
8.連表時注意條件型別需要一致
9.索引雜湊(重複少)不適於用索引,例如性別
2.命中索引
3.正確使用索引
注意事項:
like "%xx"
select * from userinfo where name like "%al";
使用函式:
select * from userinfo where reverse(name) = "zhang333";
or
select * from userinfo where id = 1 or email = "[email protected]";
型別不一致:
select * from userinfo where name = 999;
!=:
select count(*) from userinfo where name != "zhang";
特別的:如果是主鍵,則還是會走索引
>:
select * from userinfo where name > "zhang";
特別的:如果是主鍵或索引是整數型別,則還是會走索引
select * from userinfo where id > 123;
select * from userinfo where num > 123;
order by:
select * from userinfo order by name desc;
當根據索引排序時,選擇的對映如果不是索引,則不走索引
特別的:如果對主鍵排序則還是會走索引
select * from userinfo order by nid desc;
組合索引最左字首:
然後組合索引為:(name,email);
name and email 使用索引
name 使用索引
email 不使用索引
對於建立索引,它是真實存在的,佔用硬碟空間,儘量不要使用索引
select * from big_data where id > 2000010 limit 10;
select * from (select * from big_data where id > 2000020 limit 30) as A order by id desc limit 10;