mysql簡介-1

MYSQL介紹

  MySQL一般特製完整的MySQLRDBMS,是一個開源的關係型數據庫管理系統(Relational Database Management System),現在屬於Oracle公司。隨着MySQL功能的不斷完善,性能不斷提高,又有開源免費的優勢,越來越多的企業選擇使用MySQL,而放棄商用收費的Oracle,目前最新版爲:5.8

MYSQL體系

mysql結構體系::分兩層:mysql server層、存儲引擎層
   mysql server層: 分兩層:連接層、SQL層
        連接層: 
            通信協議:兼容性
            線程處理: 連接線程分配,一個線程對應一個邏輯CPU,並會在多個邏輯CPU之間進行切換
            用戶名密碼:用戶密碼判斷,以及授權信息
        SQL層:權限判斷、查詢緩存、解析器、預處理、查詢優化器、緩存和執行計劃
    存儲引擎層: MYisam、innodb、NDB、.....

mysql簡介-1

1、MYSQL安裝前配置

1.1、swap分區設置

  swappiness對swap分區有很大的影響性,它這有兩個極限值 0:最大限度使用物理內存, 100:積極使用swap分區,這裏建議不用swap分區或分配4G內存空間
cat /proc/sys/vm/swappiness

1.2、操作系統的限制

ulimit -a查看
# 最大打開文件個數,如果文件打開句柄超過1024就會報錯
    open files                      (-n) 1024
# 使用最大的進程數,最大進程7279
    max user processes              (-u) 7279
可以編輯 /etc/security/limits.conf加入限制的內容
*    soft       noproc   65535
*    head       noproc   65535
*    soft       nofile   65535
*    head       nofile   65535
\# 修改完之後重啓系統纔會生效

1.3、mysql讀取配置文件順序

Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/local/mysql/etc/my.cnf ~/.my.cn

1.4、mysql啓動選項

1、 defaults-file: 使用指定的配置文件
2、 defaults-extra-file: 除了讀取默認的配置文件,還讀取額外的配置文件
3、 no-defaults: 忽略所有的配置文件
如果一次性指定多個配置文件,則以最後一次讀取的爲準 

1.5、my.cnf配置

my.cnf 大部分來自騰訊MYSQL的優化配置

[mysqld]
basedir=/usr/local/mysql
datadir=/data/mysql
socket=/tmp/mysql.sock
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mariadb according to the
# instructions in http://fedoraproject.org/wiki/Systemd

auto_increment_increment=1
auto_increment_offset=1
back_log=210
character_set_server=UTF8
concurrent_insert=AUTO
connect_timeout=10
default_week_format=0
div_precision_increment=4
event_scheduler=OFF
group_concat_max_len=1024
innodb_adaptive_hash_index=ON
innodb_autoinc_lock_mode=1
innodb_concurrency_tickets=5000
innodb_flush_log_at_trx_commit=2
innodb_ft_max_token_size=84
innodb_ft_min_token_size=3
innodb_large_prefix=OFF
innodb_lock_wait_timeout=7200
innodb_max_dirty_pages_pct=75
innodb_old_blocks_pct=37
innodb_old_blocks_time=1000
innodb_open_files=1024
innodb_print_all_deadlocks=OFF
innodb_purge_batch_size=300
innodb_purge_threads=1
innodb_read_ahead_threshold=56
innodb_read_io_threads=12
innodb_rollback_on_timeout=OFF
innodb_stats_on_metadata=OFF
innodb_strict_mode=ON
innodb_table_locks=ON
innodb_thread_concurrency=0
innodb_thread_sleep_delay=10000
innodb_write_io_threads=12
interactive_timeout=3600
lock_wait_timeout=31536000
log_queries_not_using_indexes=OFF
long_query_time=10.000000
low_priority_updates=OFF
lower_case_table_names=0
max_allowed_packet=1073741824
max_connect_errors=999999999
max_connections=800
max_length_for_sort_data=1024
max_prepared_stmt_count=16382
max_user_connections=0
net_read_timeout=30
net_retry_count=10
net_write_timeout=60
open_files_limit=102400
query_alloc_block_size=8192
query_cache_limit=1048576
query_cache_size=0
query_cache_type=OFF
query_prealloc_size=8192
slow_launch_time=2
sql_mode=NO_ENGINE_SUBSTITUTION
sync_binlog=0
table_definition_cache=768
table_open_cache=512
tmp_table_size=209715200
wait_timeout=3600
[mysqld_safe]
log-error=/data/mysql/mariadb.log
pid-file=/data/mysql/mariadb.pid

2、安裝

mysql 5.6可以直接用mysql_install_db安裝這裏就不在講解

2.1、MYSQL5.7安裝

  安裝前需瞭解:5.7安裝初始化已經廢棄了mysql_install_db這個命令

[root@do3 local]# cd /usr/local/
# 創建mysql用戶
[root@do3 local]# useradd -u 3010 mysql -s /sbin/nologin
[root@do3 local]# mkdir -p /data/mysql
# 我們直接使用mysql二進制文件安裝
[root@do3 local]# tar xf mysql-5.7.22-linux-glibc2.12-x86_64.tar.gz 
# 使用軟鏈的方式,方便下次升級
[root@do3 local]# ln -sv mysql-5.7.22-linux-glibc2.12-x86_64 mysql
"mysql" -> "mysql-5.7.22-linux-glibc2.12-x86_64"
# 設置權限
[root@do3 local]# chown mysql.mysql mysql-5.7.22-linux-glibc2.12-x86_64 -R
[root@do3 local]# chown mysql.mysql /data/mysql/ -R
[root@do3 local]# cd mysql/bin
# 增加環境變量
[root@do3 mysql]# echo "export PATH=${PWD}:\$PATH" > /etc/profile.d/mysql.sh
[root@do3 mysql]# source !$
# 這裏很重要,初始化mysql安裝
[root@do3 mysql]# mysqld --initialize --user=mysql --basedir=/usr/local/mysql --datadir=/data/mysql/
2018-04-27T12:05:57.483766Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2018-04-27T12:05:57.483806Z 0 [Warning] 'NO_AUTO_CREATE_USER' sql mode was not set.
2018-04-27T12:05:57.486165Z 0 [Warning] InnoDB: Using innodb_large_prefix is deprecated and the parameter may be removed in future releases. See http://dev.mysql.com/doc/refman/5.7/en/innodb-file-format.html
2018-04-27T12:05:59.175629Z 0 [Warning] InnoDB: New log files created, LSN=45790
2018-04-27T12:05:59.494640Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
2018-04-27T12:05:59.546806Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: 59289cc1-4a13-11e8-9261-0050568a0453.
2018-04-27T12:05:59.579060Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
2018-04-27T12:05:59.579540Z 1 [Note] A temporary password is generated for root@localhost: SdqwoGENy8+k

# 增加一個systemv風格的啓動腳本
[root@do3 bin]# cd ..
[root@do3 mysql]# vim support-files/mysql.server
修改這兩行
    basedir=/usr/local/mysql
    datadir=/data/mysql

[root@do3 mysql]# cp support-files/mysql.server /etc/init.d/mysqld
[root@do3 mysql]# chmod +x !$
[root@do3 mysql]# mkdir /var/lib/mysql
[root@do3 mysql]# chown mysql.mysql /var/lib/mysql/ -R

# 啓動服務
[root@do3 mysql]# service mysqld start
Starting MySQL.Logging to '/data/mysql/mariadb.log'.
 SUCCESS! 

2.2、MYSQL初始密碼設置

# mysql 初始密碼會在init的時候就直接設置 也可以初始化之後查看error.log文件
[root@do3 mysql]# mysql -uroot -p
Enter password:   SdqwoGENy8+k
# 進入之後第一次是需要你修改默認密碼的,強制性要求
ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.
mysql> alter  user 'root'@'localhost' identified by 'xiong123';

# 丟失root密碼設置
配置文件中新增加一行  skip-grant-tables=1
或者,直接跳過權限,這樣也能直接修改密碼
[root@do3 mysql]# mysqld_safe --defaults-file=/etc/my.cnf --skip-grant-tables &

有可能會提示這樣的錯誤
    ERROR 1290 (HY000): The MySQL server is running with the --skip-grant-tables option so it cannot execute this statement
    解決: mysql> flush privileges; 
           mysql> alter user 'root'@'localhost' identified by 'xiong123';

2.3、mysql壓力測試工具

  我們使用 sysbench這個工具
下載鏈接, 點擊下載,下載版本爲0.4.12.14

2.3.1、sysbench簡介

  sysbench是一個開源的、模塊化的、跨平臺的多線程性能測試工具,可以用來進行CPU、內存、磁盤I/O、線程、數據庫的性能測試。目前支持的數據庫有MySQL、Oracle和PostgreSQL。以下操作都將以支持MySQL數據庫爲例進行

2.3.2、安裝三部曲

1、解壓 tar xf 
2、進入目錄 ./configure --prefix=/usr/local/sysbench --with-mysql=/usr/local/mysql --with-mysql-includes=/usr/local/mysql/include --with-mysql-libs=/usr/local/mysql/lib/
3、make && make install

# 增加環境變量
[root@do3 bin]# echo "export PATH=/usr/local/sysbench/bin:$PATH" > /etc/profile.d/sysbench.sh
[root@do3 bin]#  source !$

安裝時可能會出現
    Invalid configuration `x86_64-unknown-linux-': machine `x86_64-unknown-linux' not recognized
解決:yum -y install gcc gcc-c++ automake

# 查看幫助信息,發現缺少一個包
[root@do3 sysbench]# sysbench --help
sysbench: error while loading shared libraries: libmysqlclient.so.20: cannot open shared object file: No such file or directory
解決辦法 : ln -s /usr/local/mysql/lib/libmysqlclient.so.20 /usr/lib64/libmysqlclient.so.20

2.3.3、主要參數

  --num-threads=N             number of threads to use [1]  使用最大線程
  --max-requests=N            limit for total number of requests [10000] 限制最大請求數
  --max-time=N                limit for total execution time in seconds [0] 限制最大執行時間
  --forced-shutdown=STRING    amount of time to wait after --max-time before forcing shutdown [off]  掛載多長時間然後根據在多長時間之後強制關閉
  --thread-stack-size=SIZE    size of stack per thread [32K]  線程堆棧大小 默認32K
  --init-rng=[on|off]         initialize random number generator [off]  初始化隨機數發生器 默認關閉
  --test=STRING               名稱

Compiled-in tests:
  fileio - File I/O test     IO測試
  cpu - CPU performance test   CPU測試
  memory - Memory functions speed test   內存測試
  threads - Threads subsystem performance test  線程
  mutex - Mutex performance test  測試互斥性能
  oltp - OLTP test 測試OLTP

oltp介紹,有興趣的可以看看

2.3.4、Sysbench的測試主要包括以下幾個方面:

   1、磁盤io性能
   2、cpu性能
   3、內存分配及傳輸速度
   4、POSIX線程性能
   5、調度程序性能
   6、數據庫性能(OLTP基準測試).

2.3.5 對磁盤IO性能的測試

初始化一個fileio文件
[root@do3 sysbench]# sysbench --test=fileio --file-num=16 --file-total-size=1G prepare
sysbench 0.4.12.10:  multi-threaded system evaluation benchmark

16 files, 65536Kb each, 1024Mb total
Creating files for the test...
Extra file open flags: 0
Creating file test_file.0
.....
Creating file test_file.15
1073741824 bytes written in 18.18 seconds (56.33 MB/sec).

測試讀取速度 
[root@do3 sysbench]# sysbench --test=fileio --file-total-size=1G --file-test-mode=rndrd --max-time=180 --max-requests=100000000 --num-threads=16 --init-rng=on --file-num=16 --file-extra-flags=direct --file-fsync-freq=0 --file-block-size=16384 run

180秒讀了305M,每秒1M的速度,真是慢的掉渣啊
Operations performed:  19577 reads, 0 writes, 0 Other = 19577 Total
Read 305.89Mb  Written 0b  Total transferred 305.89Mb  (1.6991Mb/sec)
  108.74 Requests/sec executed

General statistics:
    total time:                          180.0351s  
    total number of events:              19577
    total time taken by event execution: 2878.3172
    response time:
         min:                                  5.22ms   最小
         avg:                                147.03ms  平均
         max:                                927.10ms 最大
         approx.  95 percentile:             333.84ms

Threads fairness:
    events (avg/stddev):           1223.5625/47.61  事件數
    execution time (avg/stddev):   179.8948/0.09

測試完之後刪除
[root@do3 sysbench]# sysbench --test=fileio --file-num=16 --file-total-size=1G cleanup
sysbench 0.4.12.10:  multi-threaded system evaluation benchmark

Removing test files...

2.3.6、測試CPU

計算素數的時間:   不知道什麼東東, 反正這值越少越好了
來自百度的解釋 素數:在大於1的整數中,只能被1和這個數本身整除的數,如2,3,5,7,11。也叫質數。
[root@do3 sysbench]#   sysbench  --test=cpu  --cpu-max-prime=20000 run

General statistics:
    total time:                          17.6310s
    total number of events:              10000     2W個數有一萬個質數?
    total time taken by event execution: 17.6273
    response time:
         min:                                  1.67ms     
         avg:                                  1.76ms
         max:                                  2.83ms
         approx.  95 percentile:               1.80ms

Threads fairness:
    events (avg/stddev):           10000.0000/0.00
    execution time (avg/stddev):   17.6273/0.00

2.3.6、OLTP的基準測試

生成一個test的表 構建100萬行數據,也就是準備階段,注意需要先在數據庫中創建test的數據庫
sysbench --test=oltp  --oltp-table-size=1000000 --mysql-db=test --mysql-user=root --mysql-password='xiong123' prepare
sysbench 0.4.12.10:  multi-threaded system evaluation benchmark

No DB drivers specified, using mysql
Creating table 'sbtest'...
Creating 1000000 records in table 'sbtest'...

8個線程只讀模式持續時間60秒,注意帳號密碼
sysbench --test=oltp  --oltp-table-size=1000000 --mysql-db=test --mysql-user=root --mysql-password='xiong123' --max-time=60 --oltp-read-only=on --max-requests=0 --num-threads=8 run

OLTP test statistics:
    queries performed:
        read:                            1443918     讀速度
        write:                           0
        other:                           206274
        total:                           1650192
    transactions:                        103137 (1718.88 per sec.)  每秒事務 1718個
    deadlocks:                           0      (0.00 per sec.)
    read/write requests:                 1443918 (24064.32 per sec.)    
    other operations:                    206274 (3437.76 per sec.)

General statistics:
    total time:                          60.0024s
    total number of events:              103137
    total time taken by event execution: 479.6422
    response time:
         min:                                  1.05ms
         avg:                                  4.65ms
         max:                                767.15ms
         approx.  95 percentile:               5.46ms

Threads fairness:
    events (avg/stddev):           12892.1250/77.37
    execution time (avg/stddev):   59.9553/0.00

3、存儲引擎

mysql簡介-1

3.1、myisam與innodb引擎的區別

mysql簡介-1

表空間
innodb_data_file_path負責系統表空間的路徑、初始化大小、自動擴展策略
innodb_autoextend_increment 負責數據庫自動擴展大小
mysql簡介-1

默認爲10M,建議調整爲1G
mysql簡介-1

獨立表空間
設置參數 innodb_file_per_table=1 # 5.7中默認開啓
每個獨立表空間存儲對應B+樹數據、索引、和插入緩衝等信息 .frm文件中,其它的還是在.idb中
mysql簡介-1

共享表空間與獨立表空間的區別

  1. 獨立表空間每個表都有自己的表空間,並且可以實現表空間的轉移,不好的地方在於每個表文件都有.frm和.idb文件,如果單表增長過快就容易出現性能問題
  2. 共享表空間的數據和文件放在一起方便管理;
  3. 共享表空間無法在線回收空間,如果想要回收需要先將Innodb表中數據備份,刪除原表,然後再把數據導回到原表結構中一樣的新表,特別統計分析和日誌系統不太適合用共享表空間;
    綜合考慮,獨立表空間的效率,性能比共享表空間會更高一點,目前默認使用的就是獨立表空間;

3.2、redo log

  redo log 又稱重做日誌文件,用於記錄事務操作的變化,記錄的是數據修改之後的值,不管事務是否提交都會記錄下來,斷電之後 innodb存儲引擎會使用重做日誌恢復到掉電之前的狀態,以此來保證數據的完整性。
  redo log至少有兩個文件,redo log至少有兩個文件以 Ib_logfile(0-N)命名,redo log寫的方式是順序寫、循環寫,當第一個寫滿了就寫第二個,寫滿會產生切換操作,並執行checkpoing,觸發髒頁的刷新。

1) redo log通過 innodb_flush_log_at_trx_commint參數來控制,三個值0、1、2
0:每隔一秒會將redo log buffer寫入redo log文件,同時進行刷盤操作,保證數據確實已經寫入磁盤,每次事務提交並不會觸發redo log thread將日誌緩衝中的數據寫入redo log文件
1:每次提交,都會觸發redo log thread將日誌緩衝的數據寫入文件,並flush到磁盤,該設置是最安全的模式,保證數據庫在主機斷電,OS下不會丟失任務提交的證據
2:每次事務提交時,都會把redo log buffer的數據寫入redo log文件,不會同時刷新到磁盤
三種模式下:

0:性能最好,但不安全,進程崩潰會導致丟失一秒的數據
1:安全性最高,但數據性能是最慢
2:介與兩者中間     默認就是2   innodb_flush_log_at_trx_commit | 2     

2) master thread: 每秒進行刷新
3)redo log buffer: 使用超過一半的時候會觸發刷新

3.3、binlog

功能應用於備份恢復和主從複製

  它通過sync_binlog參數來決定,sync_binlog=0,當事務提交後,Mysql不做fsync之類的的磁盤同步指令刷新 binlog_cache的信息到磁盤,而讓系統自行決定,或者cache滿了才同步到磁盤;
  爲了確保安全性我們可以將sync_binlog設置爲1, 但爲了獲得更好的性能,我們可以將sync_binlog設置爲0;
  sync_binlog=0,innodb_flush_log_at_trx_commit=1這就是數據庫的雙1模式,可以確定數據庫更加安全,但無法確保性能。 sync_binlog默認爲 0

1) 主要功能
  一、可以完成主從複製功能,在主服務器上把所有修改數據的操作記錄到binlog中,通過網絡發送給從服務器,從而達到主從同步
  二、進行恢復操作,可以使用mysqlbinlog命令,實現基於時間點和位置的恢復操作
  三、mysql二進制默認是關閉的,生產環境一定要開啓
mysql簡介-1
my.cnf中添加 開啓二進制日誌,server_id在5.7中需要配置,否則啓動會一直失敗
log_bin=mysql-bin
server_id=111
mysql簡介-1

此時我們在數據中做的任何操作,在二進制日誌中都能查詢
mysql簡介-1

查看二進制日誌大小,每重啓一次它都會重新生成一個,或者觸發了最大值
mysql簡介-1
mysql簡介-1

3.4、slow log(慢查詢日誌)

慢查詢日誌,slow_query_log默認關閉,配置文件中更改一下
mysql簡介-1

慢查詢,以及SQL未建索引的被記錄。
slow_query_log=ON
log_queries_not_using_indexes=ON

慢日誌可以更好的優化數據庫的查詢速度,當查詢變慢時可以新加索引來提高速度;
日誌分析可以使用mysqldumpslow查詢,這裏我們不用它,而是直接使用percona-toolkit工具,通過命令集合下的pt-query-digest來捕獲線上的慢SQL語句,對其進行分析,下載地址,或點我下載 - 版本爲:percona-toolkit-3.0.9-1.el7.x86_64.rpm

使用yum安裝

[root@do3 tmp]# yum -y install https://www.percona.com/downloads/percona-toolkit/percona-toolkit-3.0.9/binary/redhat/7/x86_64/percona-toolkit-3.0.9-1.el7.x86_64.rpm
如果是.tar.gz的話 因爲是二進制的 直接解壓到bin目錄直接就能用

linux下percona-toolkit工具包的安裝和使用(超詳細版)

這裏主要使用 pt-query-digest,用法介紹

常用參數:
--create-review-table :當使用--review參數把分析結果輸出到表中時,如果沒有表就自動創建。
--create-history-table:當使用--history參數把分析結果輸出到表中時,如果沒有表就自動創建。
--filter :  對輸入的慢查詢按指定的字符串進行匹配過濾後再進行分析
--limit:限制輸出結果百分比或數量,默認值是20,即將最慢的20條語句輸出,如果是95%則按總響應時間佔比從大到小排序,輸出到總和達到95%位置截止。
--log=s :指定輸出的日誌文件
--history 將分析結果保存到表中,分析結果比較詳細,下次再使用--history時,如果存在相同的語句,且查詢所在的時間區間和歷史表
           中的不同,則會記錄到數據表中,可以通過查詢同一CHECKSUM來比較某類型查詢的歷史變化。
--review:將分析結果保存到表中,這個分析只是對查詢條件進行參數化,一個類型的查詢一條記錄,比較簡單。
           當下次使用--review時,如果存在相同的語句分析,就不會記錄到數據表中。
--output 分析結果輸出類型,值可以是report(標準分析報告)、slowlog(Mysql slow log)、json、json-anon,一般使用report,以便於閱讀。
--since:從該指定日期開始分析。
--until:截止時間,配合—since可以分析一段時間內的慢查詢。

查看最近24小時的慢日誌
[root@do3 mysql]# pt-query-digest --since=24h /data/mysql/do3-slow.log > query.log

第一部分
mysql簡介-1

 overall: 總共多少查詢,上面是九條
 time range : 時間 
 unique:唯一查詢時間,即對查詢條件進行參數化後,總共有多少不同的查詢,實驗爲9個
 total: 時間
 95%: 把所有值從小到大排列,位置位於95%的那個數一般最具有參與價值
 median:中位數,把所有值從小到大排列,位置位於中間的那個數

第二部分
mysql簡介-1

response:響應時長
time:該查詢在本次分析中總的時間佔比
calls:執行次數,即本次分析總共有多少條這種類型的查詢語句;
R/Call:平均每次執行的響應時間
item:查詢對象,即具體的SQL語句

第三部分
具體的SQL語句的詳細輸出結果
mysql簡介-1

3.5、碎片處理

使用delete的時候,mysql並不會將真實數據刪除,而只是將數據文件標識位刪除,當有新數據寫入時,Mysql會再次利用這些被刪除的區域;
mysql簡介-1

碎片大小=數據總大小-空際表空間大小
這裏總數爲1024 實際大小21, 不到3B

清理碎片的兩種方法
1) mysql> alter table version engine=innodb;
  這句話的作用就是重新整理一遍全表數據,整理之後的數據連續性好,全表掃描快,缺點是需要給全表加個寫鎖,需要經歷的時間長
2) 備份原表數據,然後刪掉,重新導入新表中,與原表結構一樣
3)使用pt-online-schema-change
  在線整理表結構,收集碎片,給大表添加字段和索引,避免出現鎖表導致阻塞讀寫的操作。

查看連接
mysql簡介-1

3.6、索引

普通索引創建
alter table table_name add index index_name
或
create index index_name on table_name

測試索引效果
創建一個庫
mysql> create database test;
mysql> use test;
mysql> create table te1(id int primary key not null auto_increment,name varchar(25));

mysql簡介-1

插入測試數據 、不會存儲過程直接用腳本

[root@do3 tmp]# cat tests.sh 
#!/bin/bash
#
MYSQL_USER=root
MYSQL_PASSWD=xiong123

echo `date`
for i in {1..50000};do
    user=`cat /dev/urandom | head -5 | md5sum | head -c 5`
    mysql -u${MYSQL_USER} -p${MYSQL_PASSWD} -h "192.168.9.224" -e "insert into test.te1 values (${i},'${user}')" &>/dev/null
done
echo `date`
echo "done"

5萬條數據整了8分鐘,像測試最好用存儲過程
mysql簡介-1

無索引查詢
mysql> select * from te1 ;
mysql簡介-1

查看索引
mysql簡介-1
key:null表示沒有索引

合理添加索引三個 "經常"
1) 經常被查詢的列 ( 一般放在where後面)
2) 經常用於表連接的列
3) 經常排序分組的列(order by 或者group by 後面的字段)

越靠近1說明索引效果越好
mysql簡介-1

聯合索引:必須滿足最左前綴原則,一般把選擇性高的列放在前面,一條查詢語句可以只使用索引中的一部分,但必須從最左側開始;

索引總結:優點
1)提高數據檢索效率
2)提高聚合函數效率
3)提高排序效率
4)使用覆蓋索引可以避免回表

四個不要:
1)選擇性低的字符不要創建索引
2)很少查詢的列不要創建索引(項目初期就要確定好)
3)大數據類型字段不要創建索引;
4)儘量避免不要使用NULL,應該指定列爲NOT NULL

使用不要索引的情況
1)通過索引掃描的行記錄數超過全表的30%,優化器就不會走索引,而變成全表掃描;
2)聯合索引中,第一個查詢條件不是最左索引列
3)聯合索引中,第一個索引列使用範圍查詢,只能使用到部分索引,有ICP出現範圍是指( < , = , <=, BETWEEN and )
4)模糊查詢條件列最左以通配符“%”開始 (可以考慮放到勃勃生機底裏在面)
5)兩個列索引,一個用於檢索,一個用於排序;
6)查詢字段上面有索引,但是使用了函數運算。

3.7、事務

事務務必遵循:一致性,完整性,持久性,原子性 四大特點

事務回退
mysql簡介-1

事務提交
mysql簡介-1

3.8、truncate和delete區別

1、回滾
一、delete 可以被回滾
mysql簡介-1

二、truncate不能被回滾
mysql簡介-1

2、自增
mysql簡介-1

一、delete測試 依舊從最後一位自增
mysql簡介-1

二、tuncate 從第一位開始自增
mysql簡介-1

事務隔離級別,我這裏就不在重複造輪子了;

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