Mysql基礎系列(二)

本章內容:

  • 查看\創建\使用\刪除 數據庫

  • 用戶管理及授權實戰

  • 局域網遠程連接法

  • 查看\創建\使用\刪除\清空\修改 數據庫表(是否可空,默認值,主鍵,自增,外鍵)

  • 表內容的增刪改查

  • where條件、通配符_%、限制limit、排序desc\asc、連表join、組合union

  • 查看建表語句、查看錶結構、查看是否走索引

  • 數據類型

  • 索引!

一、數據庫操作

1、查看數據庫

SHOW DATABASES;

# 默認數據庫:
  mysql - 用戶權限相關數據
  test - 用於用戶測試數據
  information_schema - MySQL本身架構相關數據

2、創建數據庫

# utf-8 編碼
CREATE DATABASE 數據庫名稱 DEFAULT CHARSET utf8 COLLATE utf8_general_ci; 
# gbk 編碼
CREATE DATABASE 數據庫名稱 DEFAULT CHARACTER SET gbk COLLATE gbk_chinese_ci;

3、使用數據庫

USE db_name;
# 可以不使用分號

 4、用戶管理

# 創建用戶
    create user '用戶名'@'IP地址' identified by '密碼';
# 刪除用戶
    drop user '用戶名'@'IP地址';
# 修改用戶
    rename user '用戶名'@'IP地址'; to '新用戶名'@'IP地址';;
# 修改密碼
    set password for '用戶名'@'IP地址' = Password('新密碼')
  
PS:用戶權限相關數據保存在mysql數據庫的user表中,所以也可以直接對其進行操作(不建議)
# 查看當前用戶
        select user();
# 查看所有用戶
        select host,user from mysql.user;
# 人性化顯示所有用戶
        SELECT DISTINCT CONCAT('User: ''',user,'''@''',host,''';') AS query FROM mysql.user;
# 查看用戶的所有權限
        show grants for 'nick'@'%';
mysql> SELECT DISTINCT CONCAT('User: ''',user,'''@''',host,''';') AS query FROM mysql.user;
+---------------------------+
| query                     |
+---------------------------+
| User: 'nick'@'%';         |
| User: 'root'@'localhost'; |
+---------------------------+
rows in set (0.00 sec)

mysql>
mysql>
mysql>
mysql>
mysql> select host,user from mysql.user;
+-----------+------+
| host      | user |
+-----------+------+
| %         | nick |
| localhost | root |
+-----------+------+
rows in set (0.00 sec)

mysql> show grants for 'nick'@'%';
+-----------------------------------------------------------------------------------------------------+
| Grants for nick@%                                                                                   |
+-----------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'nick'@'%' IDENTIFIED BY PASSWORD '*ECE7D02DCD7D4EF7CFE8E3B249FD1D5062A821F7' |
| GRANT ALL PRIVILEGES ON `kaoshi`.* TO 'nick'@'%'                                                    |
| GRANT ALL PRIVILEGES ON `xxxxx`.* TO 'nick'@'%'                                                    |
| GRANT ALL PRIVILEGES ON `xxxxxx`.`chouti` TO 'nick'@'%'                                              |
+-----------------------------------------------------------------------------------------------------+
rows in set (0.00 sec)

mysql>

5、授權管理

# 查看權限
    show grants for '用戶'@'IP地址'
# 授權
    grant  權限 on 數據庫.表 to   '用戶'@'IP地址'
# 取消權限
    revoke 權限 on 數據庫.表 from '用戶'@'IP地址'
常用權限:
            all privileges   除grant外的所有權限
            select           僅查權限
            select,insert    查和插入權限
            usage            無訪問權限

對於目標數據庫以及內部其他:
            數據庫名.*           數據庫中的所有
            數據庫名.表          指定數據庫中的某張表
            數據庫名.存儲過程     指定數據庫中的存儲過程
            *.*                 所有數據庫

對於用戶和IP:
            用戶名@IP地址         用戶只能在改IP下才能訪問
            用戶名@192.168.1.%   用戶只能在改IP段下才能訪問(通配符%表示任意)
            用戶名@%             用戶可以再任意IP下訪問(默認IP地址爲%)

權限詳情:

all privileges  除grant外的所有權限
            select          僅查權限
            select,insert   查和插入權限
            ...
            usage                   無訪問權限
            alter                   使用alter table
            alter routine           使用alter procedure和drop procedure
            create                  使用create table
            create routine          使用create procedure
            create temporary tables 使用create temporary tables
            create user             使用create user、drop user、rename user和revoke  all privileges
            create view             使用create view
            delete                  使用delete
            drop                    使用drop table
            execute                 使用call和存儲過程
            file                    使用select into outfile 和 load data infile
            grant option            使用grant 和 revoke
            index                   使用index
            insert                  使用insert
            lock tables             使用lock table
            process                 使用show full processlist
            select                  使用select
            show databases          使用show databases
            show view               使用show view
            update                  使用update
            reload                  使用flush
            shutdown                使用mysqladmin shutdown(關閉MySQL)
            super                   使用change master、kill、logs、purge、master和set global。還允許mysqladmin調試登陸
            replication client      服務器位置的訪問
            replication slave       由複製從屬使用

添加額外管理員

mysql> delete from mysql.user;
Query OK, 2 rows affected (0.00 sec)
mysql> grant all privileges on *.* to system@'localhost' identified by 'mackei' with grant option;
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
mysql> select user,host from mysql.user;
+--------+-----------+
| user   | host      |
+--------+-----------+
| system | localhost |
+--------+-----------+
row in set (0.00 sec)
mysql>

簡單示例:

grant all privileges on db1.tb1 TO '用戶名'@'IP'

            grant select on db1.* TO '用戶名'@'IP'

            grant select,insert on *.* TO '用戶名'@'IP'

             revoke select on db1.t

一般添加用戶

create user mackei@localhost identified by 'admin';
GRANT ALL ON test.* TO 'mackei'@'localhost';        #授權
show grants for admin@localhost;
flush privileges;

6、授權局域網內主機遠程連接數據庫

#百分號匹配法
    grant all on *.* to 'test'@'192.168.200.%' identified by 'test123';
#子網掩碼配置法
    grant all on *.* to 'test'@'192.168.200.0/255.255.255.0' identified by 'test123';
#刷新權限
    flush privileges;
#遠程登陸連接
    mysql -utest -ptest123 -h 192.168.200.96

 二、表操作

1、創建表

# 基本語法:
create table 表名(
    列名  類型  是否可以爲空  默認值  自增  主鍵,
    列名  類型  是否可以爲空
)ENGINE=InnoDB DEFAULT CHARSET=utf8

not null         # 不可以爲空
default 1        # 默認值爲1
auto_increment   # 自增
primary key      # 主鍵
constraint 外鍵名 foreign key (從表字段’自己‘) references 主表(主鍵字段)    # 外鍵
是否可空,
     null表示空,非字符串            
     not null    - 不可空
     null        - 可空
設置默認值,創建列時可以指定默認值,當插入數據時如果未主動設置,則自動添加默認值

create table tb1(
                nid int not null defalut 2,
                num int not null
            )
自增,如果爲某列設置自增列,插入數據時無需設置此列,默認將自增(表中只能有一個自增列)
            create table tb1(
                nid int not null auto_increment primary key,
                num int null
            )
            或
            create table tb1(
                nid int not null auto_increment,
                num int null,
                index(nid)
            )
            注意:1、對於自增列,必須是索引(含主鍵)。
                 2、對於自增可以設置步長和起始值
                     show session variables like 'auto_inc%';
                     set session auto_increment_increment=2;
                     set session auto_increment_offset=10;

                     shwo global  variables like 'auto_inc%';
                     set global auto_increment_increment=2;
                     set global auto_increment_offset=10;
主鍵,一種特殊的唯一索引,不允許有空值,如果主鍵使用單個列,則它的值必須唯一,如果是多列,則其組合必須唯一。
            create table tb1(
                nid int not null auto_increment primary key,
                num int null
            )
            或
            create table tb1(
                nid int not null,
                num int not null,
                primary key(nid,num)
            )
外鍵,一個特殊的索引,只能是指定內容
            creat table color(
                nid int not null primary key,
                name char(16) not null
            )

            create table fruit(
                nid int not null primary key,
                smt char(32) null ,
                color_id int not null,
                constraint fk_cc foreign key (color_id) references color(nid)
            )

 2、刪除表

drop table 表名

3、清空表

# 表還存在,表內容清空delete from 表名
truncate table 表名

4、修改表

# 添加列:
        alter table 表名 add 列名 類型
# 刪除列:
        alter table 表名 drop column 列名
# 修改列:
        alter table 表名 modify column 列名 類型;  -- 類型
        alter table 表名 change 原列名 新列名 類型; -- 列名,類型
# 添加主鍵:        alter table 表名 add primary key(列名);
# 刪除主鍵:        alter table 表名 drop primary key;
                    alter table 表名  modify  列名 int, drop primary key;
# 添加外鍵:        
alter table 從表 add constraint 外鍵名稱(形如:FK_從表_主表) foreign key 從表(外鍵字段) references 主表(主鍵字段);
# 刪除外鍵:
alter table 表名 drop foreign key 外鍵名稱
# 修改默認值:
        ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;# 刪除默認值:
        ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;
# 更改表名
         rename table 原表名 to 新表名;
增刪改表的字段

#增加表字段,altertable法。
1>    語法: altertable 表名 add 字段 類型 其他;
2>    插入列,名爲sex。
mysql> alter table student add sex char(4);
Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from student;
+----+----------+-----+------+------+
| id | name     | age | dept | sex  |
+----+----------+-----+------+------+
|  2 | oldsuo   |   0 | NULL | NULL |
|  3 | kangknag |   0 | NULL | NULL |
|  4 | kangkang |   0 | NULL | NULL |
+----+----------+-----+------+------+
rows in set (0.00 sec)
3>    插入名爲suo列在name後面。
mysql> alter table student add suo int(4) after name;
Query OK, 6 rows affected (0.00 sec)
Records: 6  Duplicates: 0  Warnings: 0
4>    插入名爲qq列在第一。
mysql> alter table student add qq varchar(15) first;
Query OK, 6 rows affected (0.00 sec)
Records: 6  Duplicates: 0  Warnings: 0

#更改表名字,rename法。
1>    語法: rename table 原表名 to 新表名;
2>    更改oldsuo表爲oldning。
mysql> rename table oldsuo to oldning;
Query OK, 0 rows affected (0.00 sec)
mysql> show tables;
+--------------------------+
| Tables_in_nick_defailt |
+--------------------------+
| oldning                  |
| student                  |
+--------------------------+
rows in set (0.00 sec)

#刪除表
1>    語法:drop table <表名>;
2>    刪除表名爲test表。
mysql> drop table test;
Query OK, 0 rows affected (0.00 sec)

三、表內容操作

1、增

語法:insert into 表 (列名,列名...) values (值,值,值...)

# 插入單條數據
        insert into 表 (列名,列名...) values (值,值,值...)
# 插入多條數據
       insert into 表 (列名,列名...) values (值,值,值...),(值,值,值...)
# 插入另一條語句的查詢結果
        insert into 表 (列名,列名...) select 列名,列名... from 表

2、刪

語法:delete from 表

delete from 表;
delete from 表 where id=1;

3、改

語法:update 表 set name = 'mackei' where id>1

update 表 set name = 'nick' where id>1

4、查

語法:select * from 表

select * from 表
select * from 表 where id > 1
select nid,name,gender as gg from 表 where id > 1

# as 做別名

5、條件

語法:select * from 表 where id > 1

select * from 表 where id > 1 and name != 'nick' and num = 12;    # 多個條件
select * from 表 where id between 5 and 16;                       # id在5到16之間
select * from 表 where id in (11,22,33);                          # id在元祖中
select * from 表 where id not in (11,22,33);                      # id不在元祖中
select * from 表 where id in (select nid from 表);                # id在查詢結果中

6、通配符

語法:select * from 表 where name like '_n%'

select * from 表 where name like 'ni%'  # ni開頭的所有(多個字符串)
select * from 表 where name like 's_'   # s開頭的所有(一個字符)

7、限制

語法:select * from 表 limit 9,5;

select * from 表 limit 5;            # 前5行
select * from 表 limit 9,5;          # 從第9行開始的5行
select * from 表 limit 5 offset 9    # 從第9行開始的5行

8、排序

語法:select * from 表 order by 列1 desc,列2 asc

 select * from 表 order by 列 asc             # 根據 “列” 從小到大排列
 select * from 表 order by 列 desc            # 根據 “列” 從大到小排列
 select * from 表 order by 列1 desc,列2 asc   # 根據 “列1” 從大到小排列,如果相同則按列2從小到大排序

9、分組

語法:select num from 表 group by num

select num from 表 group by num           # 根據num分組
    select num,nid from 表 group by num,nid   # 根據num和nid分組
    select num,nid from 表  where nid > 10 group by num,nid order nid desc
    select num,nid,count(*),sum(score),max(score),min(score) from 表 group by num,nid  # 內置函數
    select num from 表 group by num having max(id) > 10    # 前面計算的結果交由後面處理
 
    注:group by 必須在where之後,order by之前
count(*)、count(1) # 表示個數
sum(score)        # 表示和
max(score)        # 表示最大數
min(score)        # 表示最小數

having            # 要用前面處理結果是用having。

10、連表

語法:inner join . onleft join . onright join . on

無對應關係則不顯示
    select A.num, A.name, B.name
    from A,B
    Where A.nid = B.nid
 
    無對應關係則不顯示
    select A.num, A.name, B.name
    from A inner join B
    on A.nid = B.nid
 
    A表所有顯示,如果B中無對應關係,則值爲null
    select A.num, A.name, B.name
    from A left join B
    on A.nid = B.nid
 
    B表所有顯示,如果B中無對應關係,則值爲null
    select A.num, A.name, B.name
    from A right join B
    on A.nid = B.nid

11、組合

語法:unionunion all

組合,自動處理重合
    select nickname
    from A
    union
    select name
    from B
 
    組合,不處理重合
    select nickname
    from A
    union all
    select name
    from B


四、其它命令

1、查看建表語句

 show create table 表名\G 

mysql> use mackei_defailt
Database changed
mysql> create table student (
      id int(4) not null,
      name char(20) not null,
      age tinyint(2) NOT NULL default '0',
      dept varchar(16) default NULL
      );
Query OK, 0 rows affected (0.05 sec)
mysql> show create table student\G        #查看建表語句
*************************** 1. row ***************************
       Table: student
Create Table: CREATE TABLE `student` (      #CREATE TABLE創建表的固定關鍵字,student爲表名。
  `id` int(4) NOT NULL,                     #學號列,數字類型,長度爲4,不爲空值。
  `name` char(20) NOT NULL,                 #名字列,定長字符類型,長度20,不爲空值。
  `age` tinyint(2) NOT NULL DEFAULT '0',    #年齡列,很小的數字類型,長度爲2不爲空,默認0。
  `dept` varchar(16) DEFAULT NULL           #系別列,變長字符類型,長度16,默認爲空。
) ENGINE=MyISAM DEFAULT CHARSET=latin1      #引擎和字符集,引擎默認InnoDB,字符集lantin1。
row in set (0.00 sec)

2、查看錶結構

desc 表名;

mysql> desc student;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(4)      | NO   |     | NULL    |       |
| name  | char(20)    | NO   |     | NULL    |       |
| age   | tinyint(2)  | NO   |     | 0       |       |
| dept  | varchar(16) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
rows in set (0.04 sec)

3、查看是否走索引

 explain select * from 表名 where name ='nick' \G 

用此命令查看是否sql語句是否還有優化的餘地

mysql> explain select * from student where name ='student' \G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: student
         type: ref     #有
possible_keys: index_name
          key: index_name  #表示有,詳細見下文
       key_len: 20
          ref: const
         rows: 1           #檢索了幾行
        Extra: Using where
row in set (0.00 sec)


五、數據類型

學習新的東西自然離不開數據類型,MySQL中的數據類型還算簡單;

大致分爲數字、字符串、時間。

那就詳細看看吧:

bit[(M)]
            二進制位(101001),m表示二進制位的長度(1-64),默認m=1

        tinyint[(m)] [unsigned] [zerofill]

            小整數,數據類型用於保存一些範圍的整數數值範圍:
            有符號:
                -128 ~ 127.
            無符號:
~ 255

            特別的: MySQL中無布爾值,使用tinyint(1)構造。

        int[(m)][unsigned][zerofill]

            整數,數據類型用於保存一些範圍的整數數值範圍:
                有符號:
                    -2147483648 ~ 2147483647
                無符號:
~ 4294967295

            特別的:整數類型中的m僅用於顯示,對存儲範圍無限制。例如: int(5),當插入數據2時,select 時數據顯示爲: 00002

        bigint[(m)][unsigned][zerofill]
            大整數,數據類型用於保存一些範圍的整數數值範圍:
                有符號:
                    -9223372036854775808 ~ 9223372036854775807
                無符號:
 ~  18446744073709551615

        decimal[(m[,d])] [unsigned] [zerofill]
            準確的小數值,m是數字總個數(負號不算),d是小數點後個數。 m最大值爲65,d最大值爲30。

            特別的:對於精確數值計算時需要用此類型
                   decaimal能夠存儲精確值的原因在於其內部按照字符串存儲。

        FLOAT[(M,D)] [UNSIGNED] [ZEROFILL]
            單精度浮點數(非準確小數值),m是數字總個數,d是小數點後個數。
                無符號:
                    -3.402823466E+38 to -1.175494351E-38,
                    1.175494351E-38 to 3.402823466E+38
                有符號:
                    1.175494351E-38 to 3.402823466E+38

            **** 數值越大,越不準確 ****

        DOUBLE[(M,D)] [UNSIGNED] [ZEROFILL]
            雙精度浮點數(非準確小數值),m是數字總個數,d是小數點後個數。

                無符號:
                    -1.7976931348623157E+308 to -2.2250738585072014E-308
                    2.2250738585072014E-308 to 1.7976931348623157E+308
                有符號:
                    2.2250738585072014E-308 to 1.7976931348623157E+308
            **** 數值越大,越不準確 ****


        char (m)
            char數據類型用於表示固定長度的字符串,可以包含最多達255個字符。其中m代表字符串的長度。
            PS: 即使數據小於m長度,也會佔用m長度
        varchar(m)
            varchars數據類型用於變長的字符串,可以包含最多達255個字符。其中m代表該數據類型所允許保存的字符串的最大長度,只要長度小於該最大值的字符串都可以被保存在該數據類型中。

            注:雖然varchar使用起來較爲靈活,但是從整個系統的性能角度來說,char數據類型的處理速度更快,有時甚至可以超出varchar處理速度的50%。因此,用戶在設計數據庫時應當綜合考慮各方面的因素,以求達到最佳的平衡

        text
            text數據類型用於保存變長的大字符串,可以組多到65535 (2**16  1)個字符。

        mediumtext
            A TEXT column with a maximum length of 16,777,215 (2**24  1) characters.

        longtext
            A TEXT column with a maximum length of 4,294,967,295 or 4GB (2**32  1) characters.


        enum
            枚舉類型,
            An ENUM column can have a maximum of 65,535 distinct elements. (The practical limit is less than 3000.)
            示例:
                CREATE TABLE shirts (
                    name VARCHAR(40),
                    size ENUM('x-small', 'small', 'medium', 'large', 'x-large')
                );
                INSERT INTO shirts (name, size) VALUES ('dress shirt','large'), ('t-shirt','medium'),('polo shirt','small');

        set
            集合類型
            A SET column can have a maximum of 64 distinct members.
            示例:
                CREATE TABLE myset (col SET('a', 'b', 'c', 'd'));
                INSERT INTO myset (col) VALUES ('a,d'), ('d,a'), ('a,d,a'), ('a,d,d'), ('d,a,d');

        DATE
            YYYY-MM-DD(1000-01-01/9999-12-31)

        TIME
            HH:MM:SS('-838:59:59'/'838:59:59')

        YEAR
            YYYY(1901/2155)

        DATETIME

            YYYY-MM-DD HH:MM:SS(1000-01-01 00:00:00/9999-12-31 23:59:59    Y)

        TIMESTAMP

            YYYYMMDD HHMMSS(1970-01-01 00:00:00/2037 年某時)

六、索引

1、索引概述

索引是表的索引目錄,在查找內容之前先查目錄中查找索引位置,從而快速定位查詢數據;

可以理解成新華字典中的索引;

索引會保存在額外的文件中。

2、索引種類

一般的索引種類及功能:

  • 普通索引:僅加速查詢

  • 唯一索引:加速查詢 + 列值唯一(可以有null)

  • 主鍵索引:加速查詢 + 列值唯一 + 表中只有一個(不可以有null)

  • 組合索引:多列值組成一個索引,專門用於組合搜索,其效率大於索引合併

  • 全文索引:對文本的內容進行分詞,進行搜索 

索引合併:使用多個單列索引組合查詢搜索
覆蓋索引:select的數據列只用從索引中就能夠取得,不必讀取數據行,換句話說查詢列要被所建的索引覆蓋

a、普通索引

# 創建表 + 索引
create table in1(
    nid int not null auto_increment primary key,
    name varchar(32) not null,
    email varchar(64) not null,
    extra text,
    index ix_name (name)
)
# 創建索引
create index index_name on table_name(column_name)
# 刪除索引
drop index_name on table_name;
# 查看索引
show index from table_name;
#注意:對於創建索引時如果是BLOB 和 TEXT 類型,必須指定length。
create index ix_extra on in1(extra(32));

b、唯一索引

# 創建表 + 唯一索引
create table in1(
    nid int not null auto_increment primary key,
    name varchar(32) not null,
    email varchar(64) not null,
    extra text,
    unique ix_name (name)
)
# 創建唯一索引
create unique index 索引名 on 表名(列名)
# 刪除唯一索引
drop unique index 索引名 on 表名

c、主鍵索引

# 創建表 + 創建主鍵
create table in1(
    nid int not null auto_increment primary key,
    name varchar(32) not null,
    email varchar(64) not null,
    extra text,
    index ix_name (name)
)

OR

create table in1(
    nid int not null auto_increment,
    name varchar(32) not null,
    email varchar(64) not null,
    extra text,
    primary key(ni1),
    index ix_name (name)
)
# 創建主鍵
alter table 表名 add primary key(列名);
# 刪除主鍵
alter table 表名 drop primary key;
alter table 表名  modify  列名 int, drop primary key;

d、組合索引

組合索引是多個列組合成一個索引來查詢

應用場景:頻繁的同時使用多列來進行查詢,如:where name = 'Mackei' and age = 22。

# 創建表
create table mess(
    nid int not null auto_increment primary key,
    name varchar(32) not null,
    age int not null
)

# 創建組合索引
create index ix_name_age on mess(name,age);

如上創建組合索引之後,查詢一定要注意:

  • name and email  -- >使用索引,name一定要放前面

  • name                 -- >使用索引

  • email                 -- >不使用索引

注意:同時搜索多個條件時,組合索引的性能效率好過於多個單一索引合併。

3、相關命令

# 查看索引
    show index from  表名
 
# 查看執行時間
    set profiling = 1;  # 開啓profiling
    SQL...              # 執行SQL語句
    show profiles;      # 查看結果

4、如何正確使用索引

# like '%xx',避免%_寫在開頭
    select * from tb1 where name like '%n';

# 使用函數
    select * from tb1 where reverse(name) = 'nick';

# or
    select * from tb1 where nid = 1 or email = '[email protected]';
    注:當or條件中有未建立索引的列才失效,否則會走索引

# 類型不一致
    如果列是字符串類型,傳入條件是必須用引號引起來。
    select * from tb1 where name = 999;

# !=,不等於
    select * from tb1 where name != 'nick'
    注:如果是主鍵,則還是會走索引
        select * from tb1 where nid != 123

# >,大於
    select * from tb1 where name > 'nick'
    注:如果是主鍵或索引是整數類型,則還是會走索引
        select * from tb1 where nid > 123
        select * from tb1 where num > 123

# order by
    select email from tb1 order by name desc;
    當根據索引排序時候,選擇的映射如果不是索引,則不走索引
    注:如果對主鍵排序,則還是走索引:
        select * from tb1 order by nid desc;
 
# 組合索引最左前綴
    如果組合索引爲:(name,email),查詢使用:
    name and email       -- 使用索引
    name                 -- 使用索引
    email                -- 不使用索引

5、注意事項

# 避免使用select *
# count(1)或count(列) 代替 count(*)
# 創建表時儘量時 char 代替 varchar
# 表的字段順序固定長度的字段優先
# 組合索引代替多個單列索引(經常使用多個條件查詢時)
# 儘量使用短索引
# 使用連接(JOIN)來代替子查詢(Sub-Queries)
# 連表時注意條件類型需一致
# 索引散列值(重複少)不適合建索引,例:性別不適合

6、執行計劃

explain + 查詢SQL  用於顯示SQL執行信息參數,根據參考信息可以進行SQL優化

mysql> explain select * from testdb;
+----+-------------+---------+------+---------------+------+---------+------+------+-------+
| id | select_type | table   | type | possible_keys | key  | key_len | ref  | rows | Extra |
+----+-------------+---------+------+---------------+------+---------+------+------+-------+
|  1 | SIMPLE      | testdb | ALL  | NULL          | NULL | NULL    | NULL |    4 |       |
+----+-------------+---------+------+---------------+------+---------+------+------+-------+
row in set (1.67 sec)
id
        查詢順序標識
            如:mysql> explain select * from (select nid,name from tb1 where nid < 10) as B;
            +----+-------------+------------+-------+---------------+---------+---------+------+------+-------------+
            | id | select_type | table      | type  | possible_keys | key     | key_len | ref  | rows | Extra       |
            +----+-------------+------------+-------+---------------+---------+---------+------+------+-------------+
            |  1 | PRIMARY     | <derived2> | ALL   | NULL          | NULL    | NULL    | NULL |    9 | NULL        |
            |  2 | DERIVED     | tb1        | range | PRIMARY       | PRIMARY | 8       | NULL |    9 | Using where |
            +----+-------------+------------+-------+---------------+---------+---------+------+------+-------------+
        特別的:如果使用union連接氣值可能爲null


    select_type
        查詢類型
            SIMPLE          簡單查詢
            PRIMARY         最外層查詢
            SUBQUERY        映射爲子查詢
            DERIVED         子查詢
            UNION           聯合
            UNION RESULT    使用聯合的結果
            ...
    table
        正在訪問的表名


    type
        查詢時的訪問方式,性能:all < index < range < index_merge < ref_or_null < ref < eq_ref < system/const
            ALL             全表掃描,對於數據表從頭到尾找一遍
                            select * from tb1;
                            特別的:如果有limit限制,則找到之後就不在繼續向下掃描
                                   select * from tb1 where email = '[email protected]'
                                   select * from tb1 where email = '[email protected]' limit 1;
                                   雖然上述兩個語句都會進行全表掃描,第二句使用了limit,則找到一個後就不再繼續掃描。

            INDEX           全索引掃描,對索引從頭到尾找一遍
                            select nid from tb1;

            RANGE          對索引列進行範圍查找
                            select *  from tb1 where name < 'alex';
                            PS:
                                between and
                                in
                                >   >=  <   <=  操作
                                注意:!= 和 > 符號


            INDEX_MERGE     合併索引,使用多個單列索引搜索
                            select *  from tb1 where name = 'alex' or nid in (11,22,33);

            REF             根據索引查找一個或多個值
                            select *  from tb1 where name = 'seven';

            EQ_REF          連接時使用primary key 或 unique類型
                            select tb2.nid,tb1.name from tb2 left join tb1 on tb2.nid = tb1.nid;



            CONST           常量
                            表最多有一個匹配行,因爲僅有一行,在這行的列值可被優化器剩餘部分認爲是常數,const表很快,因爲它們只讀取一次。
                            select nid from tb1 where nid = 2 ;

            SYSTEM          系統
                            表僅有一行(=系統表)。這是const聯接類型的一個特例。
                            select * from (select nid from tb1 where nid = 1) as A;
    possible_keys
        可能使用的索引

    key
        真實使用的

    key_len
        MySQL中使用索引字節長度

    rows
        mysql估計爲了找到所需的行而要讀取的行數 ------ 只是預估值

    extra
        該列包含MySQL解決查詢的詳細信息
        “Using index”
            此值表示mysql將使用覆蓋索引,以避免訪問表。不要把覆蓋索引和index訪問類型弄混了。
        “Using where”
            這意味着mysql服務器將在存儲引擎檢索行後再進行過濾,許多where條件裏涉及索引中的列,當(並且如果)它讀取索引時,就能被存儲引擎檢驗,因此不是所有帶where子句的查詢都會顯示“Using where”。有時“Using where”的出現就是一個暗示:查詢可受益於不同的索引。
        “Using temporary”
            這意味着mysql在對查詢結果排序時會使用一個臨時表。
        “Using filesort”
            這意味着mysql會對結果使用一個外部索引排序,而不是按索引次序從表裏讀取行。mysql有兩種文件排序算法,這兩種排序方式都可以在內存或者磁盤上完成,explain不會告訴你mysql將使用哪一種文件排序,也不會告訴你排序會在內存裏還是磁盤上完成。
        “Range checked for each record(index map: N)”
            這個意味着沒有好用的索引,新的索引將在聯接的每一行上重新估算,N是顯示在possible_keys列中索引的位圖,並且是冗餘的。

詳細


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章