
*****
## 鍵表SQL
~~~
create table staffs(
id int primary key auto_increment,
name varchar(24) not null default "",
age int not null default 0,
pos varchar(20) not null default "",
add_time timestamp not null default CURRENT_TIMESTAMP
)charset utf8;
~~~
~~~
create table user(
id int not null auto_increment primary key,
name varchar(20) default null,
age int default null,
email varchar(20) default null
) engine=innodb default charset=utf8;
~~~
插入數據
~~~
insert into staffs(`name`,`age`,`pos`,`add_time`) values('z3',22,'manager',now());
insert into staffs(`name`,`age`,`pos`,`add_time`) values('July',23,'dev',now());
insert into staffs(`name`,`age`,`pos`,`add_time`) values('2000',23,'dev',now());
~~~
~~~
insert into user(name,age,email) values('1aa1',21,'b@163.com');
insert into user(name,age,email) values('2aa2',22,'a@163.com');
insert into user(name,age,email) values('3aa3',23,'c@163.com');
insert into user(name,age,email) values('4aa4',25,'d@163.com');
~~~
建立復合索引
~~~
create index idx_staffs_nameAgePos on staffs(name,age,pos);
~~~
### 口訣
全值匹配我最愛,最左前綴要遵守
帶頭大哥不能死,中間兄弟不能斷
索引列上少計算,范圍之后全失效
like百分寫最右,覆蓋索引不寫星
不等空值還有or,索引失效要少用
varchar引號不可丟,SQL高級也不難
### 練習
假設index(a,b,c)
| where語句 | 索引是否被使用到 |
| --- | --- |
| where a = 3 | Y,使用到a |
| where a = 3 and b = 5 | Y,使用到a,b |
| where a = 3 and b = 5 and c = 4 | Y,使用到a,b,c |
| where b = 3 或 where b = 3 and c = 4 或 where c = 4 | N |
| where a = 3 and c = 5 | 使用到a,c沒有被使用,b中間斷了 |
| where a = 3 and b > 4 and c = 5 | 使用到了a,b |
| where a = 3 and b like 'kk%' and c = 4 | 使用到了a,b,c |
| where a = 3 and b like '%kk' and c = 4 | 使用到了a |
| where a = 3 and b like '%kk%' and c = 4 | 使用到了a |
- 1-數據庫-基本使用
- 1-1-數據存儲
- 1-2-數據庫
- 1-3-MySQL安裝和配置
- 1-4-SQL
- 1-5-數據完整性
- 1-6-命令行操作數據庫
- 2-MySQL查詢
- 2-1-MySQL查詢
- 2-2-條件
- 2-3-聚合函數
- 2-4-分組
- 2-5-排序
- 2-6-分頁
- 2-7-連接查詢
- 2-8-子查詢
- 2-9-自關聯
- 3-MySQL外鍵
- 4-MySQL與Python交互
- 4-1-數據準備
- 4-2-數據表的拆分
- 4-3-Python操作MySQL
- 5-MySQL高級
- 5-1-視圖
- 5-2-事務
- 5-3-索引
- 5-4-賬戶管理(了解)
- 6-數據庫存儲引擎
- 6-1-MyISAM存儲引擎
- 6-2-Innodb存儲引擎
- 6-3-CSV存儲引擎
- 6-4-Memory存儲引
- 7-MySQL基準測試
- 8-explain分析SQL語句
- 8-1-影響服務器性能的幾個方面
- 8-2-explain分析SQL
- 9-索引優化案例
- 10-索引優化
- 11-排序優化
- 12-慢查詢日志
- 13-Show Profile進行SQL分析
- 14-數據庫鎖
- 15-主從復制
- 16-MySQL分區表
- 17-MySQL操作規范