一、mysql基础操作(centos5.5)
1.mysql表复制
create table t3 like t1;//f复制t1的表结构
insert into t3 select * from t1; //表结构一样的情况下可用select*
2.mysql索引
2.1 create、drop 不能用于主键创建索引
create index in_name on t1(name);
drop index in_name on t1;
create unique index un_name on t1(name);//唯一索引不能有重复值
drop index un_name on t1;
show index from t1;
2.2
alert table t1 add index in_name (name);
alert table t1 drop index in_name;
alert table t1 add unique (name);
aler table t1 drop index name;
alert tabel t1 add index in_name (name);
alert table t1 drop index inname;
alert table t1 add primary key (id );//主键索引
3.mysql视图 从一个表中通过一个条件拿出一部分符合条件的数据成为一个新表,就是视图
create view v_t1 as select * from t1 where id>4 and id <8;
select * from v_t1;//5,6,7
delete from t1 where id =6;
select * from v_t1;// 5,7 会跟随主表变化,主表被删除,视图会发生错误。
drop view v_t1;
show tables //查看视图,视图是一张表
4.mysql内置函数
4.1字符串函数
select concat ("hello","world") as myname;//连接字符串
select lcase ("MYSQL");//转小写
select ucase ("mysql");//转大写
select length ("good");//5 得到长度
select ltrim (" hello");//去左侧空
select rtrim ("hello ");//去右侧空
select repeate("hello",3);//重复3次 hellohellohello
select replace("a is not b","a","c");//c替换a
select substr("linux is good ",1,5);//linux 从1开始取5个
select space (10);//生成10个空格
select concat (space(10),"hello");
4.2数学函数
select bin (200);//十进制转二进制
select ceiling(10.10);//11
select floor(10.10);//10
max、min //聚合时使用
select sqrt (4.5);//开平方
select rand ();//返回0-1之间随机数
4.3日期函数
select curdate();
select curtime();
select unix_timestamp();
select now();
select week();//
select year("2012-10-10");
select datediff("2012-10-10","2012-10-15");//天数差
5.mysql预处理语句 ?prepare 变量变时可以不用每次都请求数据库
prepare stmt1 from "select * from t1 where id >?";
set @i=1;
execute stmt1 using @i;//执行
drop prepare stmt1;
6.mysql事务处理 //myisam引擎不支持事务,innodb
set autocommit =0;//设置不自动提交
delete from t1 where id >5;
rollback;
commit;
savepoint p1;
insert into t1(name) values(user8);
savepoint p2;
rollback to p1;
commit;//没有user8
7.mysql存储 procedure 相当于一代码段
往t2插入100条
\d //
create procedure p2()
begin
set @i=3;
while @i<100
do
insert into t2(name) values (concat("user",@i));
set @i=@i+1;
end while ;
end //
\d;
show procedure status;
call p2();
8.mysql触发器 对t1表操作时,t2也进行一定操作
truncate t2;//数据量大时删除方式
8.1 \d //
create trigger t1 before insert on t1 for each row
begin
insert into t2(name) values (new.name);
end//
\d; //表1插入数据,表2也跟着插入
8.2 \d //
create trigger t2 before delete on t1 for each row
begin
delete from t2 where name =(old.name);
end //
\d;
delete from t1 where name="user2";
8.3 \d //
crate trigger t3 before update on t1 for each row
begin
update t2 set name =(new.name ) where name =(old.name)
end //
\d ;
update t1 set name ="user30" where name="user3"; //表1、2都变未user30
9.重排auto_increment
清空表时 delete时一条一条删除而且不会回复auto_increment,
truncate 可以可以将auto_increment 恢复成1;
或者用alert table tablename auto_increment =1;