1、复制表结构+表数据
Mysql> create tables t2 like t1;
Mysql> insert into t2 select * from t1;
2、mysql索引
a、Alert Table 用来创建普通索引、Unique唯一索引(当前列数值不可重复)或Primary Key 主键索引
Mysql> alter table table_name add index index_name(column_list)
Mysql> alter table table_name add Unique(column_list)
b、creat index (不可处理主键索引)
Mysql> create index index_name on table_name(column_list)
Mysql> create Unique index index_name on table_name(column_list)
c、drop index(不可处理主键索引)
Mysql> drop index index_name on table_name
d、alter table drop
Mysql> alter table table_name drop index index_name
Mysql> alter table table_name drop primary key
3、mysql视图
创建视图 (视图可根据主表实时更新)
Mysql> create view v_t1 as select * from t1 where id>4 and id <11;
Mysql> show tables;
Mysql> show create view v_t1;
Mysql> drop view v_t1;
4、Mysql 内置函数
concat ("string1","string2") //链接字符串
lcase(STRING) //转换小写
ucase(string) //转换大写
length(string) //string长度
ltrim( string) //去除string前面空格
rtrim(string ) //去除string后面空格
repeat(string,count) //重复string count次
replace(str,search_str,replace_str) //str中用replace_str替换search_str
5、mysql预处理语句
设置stmt1预处理,传递一个数据作为where判断条件
Mysql> prepare stmt1 from 'select * from t1 where id>?';
设置一个变量
Mysql> set @i=5;
执行stmt1预处理
Mysql> execute stmt1 using @i;
删除预处理stmt1
Mysql> drop prepare stmt1;
6、mysql事务处理(Engine=MyISAM表引擎不支持事务机制)
查看表引擎是否支持
Mysql> show create table t1;
设置表引擎为innodb
Mysql> alter table t1 engine=innodb;
关闭自动提交功能
Mysql> set autocommit=0;
查看当前autocommit设置
Mysql> select @@autocommit;
提交
Mysql> commit;
从表t1中删除了一条记录
Mysql> delete from t1 where id =11;
此时做一个p1还原点
Mysql> savepoint p1;
再次从表t1中删除一条记录
Mysql> delete from t1 where id =10;
再次做一个p2还原点
Mysql> savepoint p2;
此时恢复到p1还原点,当然后面p2这些还原点自动失效
Mysql> rollback to p1;
退回到最原始的还原点
Mysql>roolback;
7、Mysql 存储(批量处理)
例子:创建存储P1,创建100个用户;
Mysql> \d // 执行“;”临时替换为“//”
Mysql> create proceduce p1()
->begin
->set @i=1;
->while @i<100 do
->insert into t1(name) value(concat("user",@i));
->set @i=@i+1;
->end while;
->end//
Mysql> \d ;
查看存储
Mysql> show procedure status\G
Mysql> show create procedure p1\G
执行
Mysql> call p1();
8、Mysql触发器
修改delimiter为//
Mysql> \d //
例子:创建触发器tg1,当向t1表插入数据时,t2表也被插入数据
Mysql> create trigger tg1 before insert on t1 for each row
->begin
->insert into t2(name) values(new.name);
->end//
Mysql> \d ;
查看触发器
Mysql> show triggers;
删除触发器
Mysql> drop trigger tg1;
创建触发器tg2,当向t1表删除数据时,t2表也被删除数据
Mysql> create trigger tg2 before delete on t1 for each row
->begin
->delete from t2 where name=old.name;
->end//
创建触发器tg3,当向t1表更新数据时,t2表也被更新数据
Mysql> create trigger tg3 before update on t1 for each row
->begin
->update t2 set name=new.name where name=old.name;
->end//
9、重排auto_increment
Mysql数据库自动增长的ID恢复重新排序
Mysql> alter table tablename auto_increment = 1;
Other:
联合查询
Mysql> select * from t1 union select *from t2
快速删除
Mysql> truncate table tablename;