MySQL學習筆記_9_MySQL進階操作(上)

來源:互聯網
上載者:User

標籤:mysql   sql   視圖   索引   函數   

MySQL進階操作(上)



一、MySQL表複製

create table t2 like t1;               #複製表結構,t2可以學習到t1所有的表結構

insert into t2 select * from t1;    #複製表資料,但是這樣還是會有缺陷,因為沒有考慮到列的對應,因為t1與t2的表結構完全一致,所以此次操作才不會出錯!

建議:

insert into t3(name) select name from t1; #指定複製的列


二、MySQL索引

1、直接建立索引

create index index_name on table_name(column_list);                #建立普通索引

create unique index index_name on table_name(colume_list);    #建立唯一索引,請在建立唯一索引之前確保該列沒有重複值,不然,建立不成功!


2、直接刪除索引

drop index index_name on table_name;


3、修改-建立索引

alter table table_name add index [index_name](colum_list);                #建立普通索引

alter table table_name add unique [index_name](column_list);            #建立唯一索引

alter table table_name add primary key [index_name](column_list);   #建立主鍵索引,如果不添加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視圖

視圖:通過一個條件,把一部分資料從一張表裡面提取出來,形成一張中間表,這張表就是視圖

注意:視圖隨著主表的改變而改變

1、建立視圖

create view view_nameas select *from table_naem where id > 4 and id <= 10;


3、查看建立了哪些視圖

showtables; #視圖就是一個中間表

3、查看視圖中資料

select* from view_name; #與查看錶資料相同


4、刪除視圖

drop view view_name;


四、MySQL內建函數補充

查看函數作用及簡單樣本:? function_name

e.g. ? lcase;


1、字串函數

1)lcase(“string”)/ucase(“string”)           #轉換成小寫/大寫,與lower(str)/upper(str)作用相同

2)length(“string”)                                   #返回字串的長度

3)repeat(“string”,n)                                #將字元從重複n次

4)space(n)                                               #產生n個空格


2、數學函數

1)bin(decimal_number)                          #十進位轉二進位

2)ceiling(n)                                             #作用與ceil相同,向下取整

3)sqrt(n)                                                  #開平方

4)max(col)/min(col)                               #取最大/最小值,彙總時使用

5)rand()                                                   #產生隨機數

select * from table_name order by rand(); #使用rand函數作為排序基準


3、日期函數

1)datediff(expr1,expr2)                             #返回expr1和expr2相差的天數,如果expr1> expr2,則返回正值

MySQL學習筆記_9_MySQL進階操作(上)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.