---
title: "mysql常用命令"
author: "香水浓"
date: "2015-05-24T02:01:37Z"
tags: ["MySQL"]
categories: ["数据库"]
slug: "mysql"
draft: false
lastmod: "2015-05-30T14:07:07Z"
id: 2213776
url: "https://794818247.iteye.com/blog/2213776"
---

连接数据库
mysql -u troy -ptroy

备份表
mysqldump -u troy -ptroy mm_database mm_user_tbl > user.sql

恢复表（与恢复数据库命令相同）
mysql -u troy -ptroy mm_database < user.sql
 
备份数据库
mysqldump -u troy -ptroy mm_database > mm.sql

恢复数据库
mysql -u troy -ptroy mm_database < mm.sql

显示所有数据库
show databases 

显示所有表
show tables 

显示表的schema
describe mm_user_tbl 

改变表名
alter table mm_user_tbl rename user_tbl 

创建授权
grant select on 数据库.* to 用户名@登录主机 identified by \"密码\" 

修改密码
mysqladmin -u用户名 -p旧密码 password 新密码 

执行sql
mysql -h localhost -u troy -ptroy mysql -e "show tables;"

查询当前用户
select current_user;

如果数据库不存在则创建
create database if not exists xmpl;

删除用户（并不知道该用户是否存在）
grant select on xmpl.* to batch@'%', batch@'localhost';
drop user batch@'%', batch@'localhost';

赋权限
grant all privileges on xmpl.* to batch@'%' identified by 'batch';
grant all privileges on xmpl.* to batch@'localhost' identified by 'batch';

查看权限
show grants for troy;

查询前两条记录
select * from users_tbl limit 2;

中文乱码问题
建表时指定<span style="color:red">DEFAULT CHARSET=utf8;</span>

索引
alter table primary_vocabulary_tbl add unique index index_uniq_vocab_word(word);
alter table primary_vocabulary_tbl add unique index (word);
show index from primary_vocabulary_tbl; --通过查询出来的索引名再删除
alter table primary_vocabulary_tbl drop index index_uniq_vocab_word;

增删改列
create table secondary_test_tbl(id int not null primary key);
alter table secondary_test_tbl add column name varchar(20) unique;
alter table secondary_test_tbl drop column name;
alter table primary_user_tbl change username user_name varchar(20);


查看存储过程
show procedure status; --查看所有
show procedure status where db='xmpl'; --查看指定数据库
show create procedure mockup_test_data_sp;

修改表，增加id属性为auto_increment自动增长
alter table secondary_test_tbl change id id int not null auto_increment

外键
alter table primary_role_resource_mapping_tbl add constraint fk_role_id foreign key (role_id) references primary_role_tbl(id);

alter table primary_role_resource_mapping_tbl add constraint fk_role_id foreign key (role_id) references primary_role_tbl(id);

alter table primary_role_resource_mapping_tbl drop foreign key fk_role_id;

show create table primary_role_resource_mapping_tbl;

修改表charset
alter table primary_role_resource_mapping_tbl default charset = utf8;
alter table primary_role_resource_mapping_tbl default character set utf8;