这些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();
相关文章
相关标签/搜索