這些Mysql經常使用命令你是否還記得?

前言

記錄mysql經常使用命令操做mysql

基礎操做
  • 命令行登陸mysql
 mysql -u用戶名 -p用戶密碼
  • 爲表增長建立時間和更新時間
ALTER TABLE order_info_tbl ADD COLUMN create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '建立時間';

ALTER TABLE order_info_tbl ADD COLUMN update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時間'
修改密碼
  • 普通
update user set password=password("root1234") where user="root";
  • 帶插件
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY ''root;
表分區
  • 數據按照31個省份分區
ALTER TABLE tache_stat_tbl_20190120 PARTITION BY HASH(province) PARTITIONS 31
表、索引、執行計劃
  • 表空間的狀況查看(指定數據庫)
select TABLE_NAME, concat(truncate(data_length/1024/1024,2),' MB') as data_size,
concat(truncate(index_length/1024/1024,2),' MB') as index_size
from information_schema.tables
# where TABLE_SCHEMA = 'yourdb'
group by TABLE_NAME
order by data_length desc;
  • 索引的創建

儘可能避免廉價的創建索引,能夠先根據數據區分度來判斷,是否有必要創建索引。sql

select count(distinct 將要創建索引的字段) / count(*)
  • 執行計劃的extra的幾種類型解讀

Using index
表示使用了覆蓋索引(Covering Index)數據庫

Using where
Using where的做用提示了用where來過濾結果集。服務器

Using temporary
說明MySQL須要使用臨時表來存儲結果集,常見於排序和分組查詢app

Using filesort
MySQL中沒法利用索引完成的排序操做稱爲「文件排序」socket

經常使用維護操做
  • 查詢執行時間超過2分鐘的線程,而後拼接成 kill 語句
select concat('kill ', id, ';') from information_schema.processlist where command != 'Sleep' and time > 2*60 order by time desc
  • 爲用戶授予全部權限
GRANT ALL PRIVILEGES ON *.* TO 'YourUserName'@'%' IDENTIFIED BY "YourPassword";
數據導入導出
  • 導出包括系統庫在內的全部數據庫數據
mysqldump -uroot -proot --all-databases >/all.sql
  • 只導出表結構,不導出數據
mysqldump -uroot -proot --no-data --databases db1 > /table_with_no_data.sql
  • 跨服務器導出導入數據,目標數據庫必須存在,不然會報錯
mysqldump --host=h1 -uroot -proot --databases db1 |mysql --host=h2 -uroot -proot db2
  • 導出數據時報mysql.sock錯的幾種解決方案

默認狀況下,鏈接協議爲socket,如遇到下述錯誤,能夠嘗試更換協議。tcp

mysqldump: Got error: 2002: "Can't connect to local MySQL server through socket 
'/var/lib/mysql/mysql.sock'

方案一:重啓數據庫會從新建立mysql.sock。
方案二:若暫時沒法重啓數據庫,能夠經過TCP協議鏈接數據庫。
--protocol=name     The protocol to use for connection (tcp, socket, pipe,memory).
樣例語句:函數

mysqldump -h127.0.0.1  -uroot -proot --protocol=TCP --database db1 
--tables  conf_area_tbl  conf_app_tbl > 1.sql
  • 導出存儲過程和自定義函數
mysqldump  -uroot -p --host=localhost --all-databases --routines
  • 終端執行sql,將結果輸出到文件
mysql -uroot -e 'select * from cb_mon.t_book limit 10' > mytest.txt
  • 使用存儲過程批量生成數據
DROP PROCEDURE if exists test_insert ;
DELIMITER ;;
CREATE PROCEDURE test_insert ()
BEGIN

DECLARE i INT DEFAULT 1;# can not be 0
WHILE i<1000
DO

insert into SS_BOOK values (i, CONCAT("00000",i) , CONCAT('book',i), 1, CONCAT('book_description',i));

SET i=i+1;
END WHILE ;
commit;
END;;
CALL test_insert();