1.MySQL基础操作
一:MySQL基础操作
1:MySQL表复制
复制表结构 + 复制表数据
create table t3 like t1; --创建一个和t1一样的表,用like(表结构也一样)
insert into t3 select * from t1; --t1的数据全部拿过来,注意是表结构一致才select* ,否则选择相应的的字段列插入
create table t1(
id int unsigned not null auto_increment primary key,
name varchar(30)
);
2:MySQL索引(create不能创建主键索引,得用alter,建议全部用alter创建索引)
*设置主键后默认就是主键索引
一:alter table用来创建普通索引,unique索引或primary key索引
普通索引:alter table t1 add index in_name(name) --t1表中的那么字段添加索引名为in_name
唯一索引:alter table t1 add unique(name) --不给名字,默认是字段名
alter table t1 add unique un_name(name)
主键索引(自增才有意义):alter table t1 add primary key(id)
主键索引不是自增记得改成自增:alter table t1 modify id int unsigned not null auto_increment;
查看:show index from t1;
删除:alter table t1 drop index in_name;
@*删除主键索引单独处理*
二:alter table table_name drop index index_name
alter型删除索引:alter table t1 drop index in_name;
@*删除主键索引*:
注意:删除主键索引的时候,如果你的主键索引是自增(如:id)删除是会报错的
实在想玩的话就把主键的auto_increment消掉
alter table t1 modify id int unsigned not null;
接着删除主键:alter table t1 drop primary key;
改成自增:alter table t1 modify id int unsigned not null auto_increment;
三:create index(不常用学习下,不能对主键索引操作,只能操作普通和唯一索引)
*创建普通索引: create index in_name on t1(name); --将t1表中的那么字段添加为普通索引
查看索引: show index from t1;
删除索引: drop index in_name on t1; --t1表中的in_name索引删除
->在做唯一索引之前字段不能有重复值,否则创建不成功
*创建唯一索引: create unique index un_name on t1(name);
四:删除create创建的索引:drop index
drop index in_name on t1;
3:MySQL视图
定义:视图是一个虚拟表,其内容由查询定义,是根据建立视图的sql语句拿到的数据保存在一张表中而创建的表-视图
*根据从表里面拿出来的数据而创建出来的一张表
创建视图:create view v_t1 as select * from t1 where id>4 and id<11;
作用:
如果 t1表里的数据某条记录被删除了,那么视图v_t1表的对应数据也会删除,类似主从(主表无则从无)
所以:视图也可以充当一个中间表:查数据的时候可以不去查主t1 去查视图表v_t1
*视图表示依赖于,创建时sql的表t_name,如果表t_name损坏的了(删除了),对应的视图将会发生错误不能使用
查看视图:show tables;
删除视图:drop view v_t1;
视图帮助信息:?view;
4:MySQL内置函数
字符串函数:
select concat("hello","word"); 链接字串 ->hello world
lcase("MYSQL") 转换成小写
ucase("mysql") 转换成大写
length("leyangjun") string长度
ltrim(" userName") 去除前端空格
rtrim("userName ") 去除后端空格
repeat("linux",count) 重复count次( select repeat('d',2);重复输出2次dd)
replace(str,search_str,replace_str) 在str中使用replace_str替换search_str
substring(str,position[length]) 从str的position开始,取length个字符串->substring 和 substr一样
select substr("leyangjun",1,5); 从第一个开始取5个字符串
space(count) 生成count(数字)个空格
数学函数
bin(decimal_number) 十进制转二进制(select bin(120);)
ceiling(number2) 向上取整(select ceiling(10.10);--->11)
floor(number2) 向下取整(select ceiling(10.10);--->10)
Max(列) 取最大值
MIN(列) 取最小值
sqrt(number2) 开平方
rand() 返回0-1内的随机值
日期函数:
curdate(); 返回当前日期
curtime(); 返回当前时间
now(); 返回当前的日期和时间
unix_timestamp(date) 返回date的unix时间戳
from_unixtime() 返回unix时间戳日期值
week(date) 返回日期date为一年中的第几周
year(date) 返回日期中的年份
datediff(expr,expr2) 返回起始时间expr和结束时间expr2间隔天数select datediff("2014-08-03","2014-08-04");
5:MySQL预处理语句
一:设置一个预处理语句:prepare stmt1 from 'select * from t1 where id>?';
二:设置一个变量:set @=i1;
三:执行stmt1预处理:execute stmt1 using @i;
设置@i=5
set @i=5;
execute stmt1 using @i;
删除预处理:
drop prepare stmt1;
应用场景:比如你是老板我要看1,2,3,4,5,6、、、、12月份入职人员的情况
*就可以把SQL做成预处理,这样就不需要每次去请求