MySQL学习笔记_9_MySQL高级操作(上)
MySQL高級操作(上)
一、MySQL表復制
create table t2 like t1; ? ? ? ? ? ? ? #復制表結(jié)構(gòu),t2可以學習到t1所有的表結(jié)構(gòu)
insert into t2 select * from t1; ? ?#復制表數(shù)據(jù),但是這樣還是會有缺陷,因為沒有考慮到列的對應,因為t1與t2的表結(jié)構(gòu)完全一致,所以此次操作才不會出錯!
建議:
insert into t3(name) select name from t1; #指定復制的列
二、MySQL索引
1、直接創(chuàng)建索引
create index index_name on table_name(column_list); ? ? ? ? ? ? ? ?#創(chuàng)建普通索引
create unique index index_name on table_name(colume_list); ? ?#創(chuàng)建唯一索引,請在創(chuàng)建唯一索引之前確保該列沒有重復值,不然,創(chuàng)建不成功!
2、直接刪除索引
drop index index_name on table_name;
3、修改-創(chuàng)建索引
alter table table_name add index [index_name](colum_list); ? ? ? ? ? ? ? ?#創(chuàng)建普通索引
alter table table_name add unique [index_name](column_list); ? ? ? ? ? ?#創(chuàng)建唯一索引
alter table table_name add primary key [index_name](column_list); ? #創(chuàng)建主鍵索引,如果不添加index_name,則使用column_list作為默認索引名
4、修改-刪除索引
alter table table_name drop index index_name; ? ? ? ? ? ?#刪除普通/唯一索引
alter table table_name drop primary key; ? ? ? ? ? ? ? ? ? ? ?#刪除主鍵索引
【推薦使用方式3、4】
【附】
1、查看索引:show index from t1 \G
2、alter table table_name modify id int not null;
三、MySQL視圖
視圖:通過一個條件,把一部分數(shù)據(jù)從一張表里面提取出來,形成一張中間表,這張表就是視圖
注意:視圖隨著主表的改變而改變
1、創(chuàng)建視圖
create view view_name as select *from table_naem where id > 4 and id <= 10;
3、查看創(chuàng)建了哪些視圖
showtables; #視圖就是一個中間表
3、查看視圖中數(shù)據(jù)
select* from view_name; #與查看表數(shù)據(jù)相同
4、刪除視圖
drop view view_name;
四、MySQL內(nèi)置函數(shù)補充
查看函數(shù)作用及簡單示例:? function_name
e.g. ? lcase;
1、字符串函數(shù)
1)lcase(“string”)/ucase(“string”) ? ? ? ? ? #轉(zhuǎn)換成小寫/大寫,與lower(str)/upper(str)作用相同
2)length(“string”) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #返回字符串的長度
3)repeat(“string”,n) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?#將字符從重復n次
4)space(n) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #生成n個空格
2、數(shù)學函數(shù)
1)bin(decimal_number) ? ? ? ? ? ? ? ? ? ? ? ? ?#十進制轉(zhuǎn)二進制
2)ceiling(n) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #作用與ceil相同,向下取整
3)sqrt(n) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?#開平方
4)max(col)/min(col) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #取最大/最小值,聚合時使用
5)rand() ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #生成隨機數(shù)
select * from table_name order by rand(); #使用rand函數(shù)作為排序基準
3、日期函數(shù)
1)datediff(expr1,expr2) ? ? ? ? ? ? ? ? ? ? ? ? ? ? #返回expr1和expr2相差的天數(shù),如果expr1> expr2,則返回正值
轉(zhuǎn)載于:https://blog.51cto.com/zhujifang/1380131
總結(jié)
以上是生活随笔為你收集整理的MySQL学习笔记_9_MySQL高级操作(上)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MBA智库百科
- 下一篇: poj 3565 uva 1411 An