數(shù)據(jù)庫基本操作
一、數(shù)據(jù)庫的基本操作
1、查看所有的數(shù)據(jù)庫:show databases;
2、創(chuàng)建數(shù)據(jù)庫:create database 數(shù)據(jù)庫名字;
3、選中數(shù)據(jù)庫:use 數(shù)據(jù)庫名字;
4、刪除數(shù)據(jù)庫:drop database 數(shù)據(jù)庫名字;
二、表的操作
1、查看所有的表:show tables;
2、創(chuàng)建表:create table 表名 (字段1 數(shù)據(jù)類型1,字段2 數(shù)據(jù)類型2……)
3、修改表:alter table
(1)增加字段:alter table 表名 add (字段1 數(shù)據(jù)類型1,字段2 數(shù)據(jù)類型2……)
(2)刪除字段:alter table 表名 drop 字段1,drop 字段2;
(3)修改字段名稱:alter table 表名 change 舊字段 新字段 數(shù)據(jù)類型;
(4)修改數(shù)據(jù)類型:alter table 表名 modify 字段 新數(shù)據(jù)類型;
(5)重命名:alter table 表名 rename 新表名;
4、刪除表:drop table 表名;
5、復(fù)制表:create table 表名 as select * from 表名2 where 條件;
6、查看表的結(jié)構(gòu):desc/describe 表名;
三、數(shù)據(jù)的操作
1、插入數(shù)據(jù):insert into 表名 values (值1,值2……)
2、更新數(shù)據(jù):update 表名 set 字段=值 where 條件
3、刪除數(shù)據(jù):delete from 表名 where 條件
4、查找數(shù)據(jù):select */字段 from 表 where 條件
(1)條件:>、<、=、!=、<>、>=、<=、in (值1,值2……)、not in (值1,值2……)、between and、like %
(2)聚焦函數(shù):sum、count、avg、max、min
(3)分組:select 字段,聚焦函數(shù) from 表 group by 字段
(4)連接:
內(nèi)連接:join、 where
select */字段 from 表1 join 表2 on 條件1 join 表3 on 條件2;
select */字段 from 表1,表2…… where 條件1 and 條件2;
外連接:left、right
select */字段 from 表1 (left/right) join 表2 on 條件1 (left/right)join 表3 on 條件2;
(5)合并:select */字段 from 表1 union select */字段 from 表2……;
(6)查找唯一性數(shù)據(jù):select distinct */字段 from 表 where 條件;
(7)限制查找:
查找前n行:select */字段 from 表 limit n;
查找a+1行a+b行:select */字段 from 表 limit a,b;
(8)排序:select */字段 from 表 order by 字段 (升序asc/降序desc)
五、索引和視圖
(一)索引
1、創(chuàng)建索引
(1)在已創(chuàng)建的表里創(chuàng)建索引:create index 索引名 on 表名(字段);
(2)在創(chuàng)建表的時候創(chuàng)建索引:create table 表名 (字段1 數(shù)據(jù)類型1,字段2 數(shù)據(jù)類型2……,d xsxxvs
index 索引名(字段));
(3)alter table 創(chuàng)建索引:alter table 表名 add (index 索引名1(字段1),index 索引名2(字段2)……);
2、查看索引:show index from 表名;
3、刪除索引:drop index 索引名 on 表名;
同時刪除多個索引:alter table 表名 drop index 索引名1,drop index 索引名2;
(二)視圖
1、創(chuàng)建視圖:create view 視圖名 as select */字段 from 表 where 條件
2、查找視圖:select */字段 from 視圖 where 條件
3、刪除視圖:drop view 視圖名字
六、函數(shù)
取字符函數(shù)
1、substring(字段,a,b):從第a個字符開始,取b個字符
2、left(字段,n):從左邊取n個字符
3、right(字段,n):從右邊取n個字