MySQL常用操作
表記錄管理
1. insert 插入
insert into 表名 values(值1),(值2),...;
insert into t1 values(1, 'Lucy', 90),(2, 'Green',86);
insetr into 表名(字段1,...) values(值1),...;
insert into t1(name,score) values('Peter',100); # id默認爲空
2. select 查詢
select * from 表名 [where 條件];
select 字段1,字段2, from 表名 [where 條件];
3. alter 修改
alter table 表名 執行動作;
添加字段(add)
alter table 表名 add 字段名 數據類型;
alter table 表名 add 字段名 數據類型 first;
alter table 表名 add 字段名 數據類型 after 字段名;
刪除字段(drop)
alter table 表名 drop 字段名;
修改類型(modify)
alter table 表名 modify 字段名 新數據類型;
表重命名(rename)
alter table 表名 rename 新表名;
4. 刪除表記錄
delete from 表名 where 條件;
注意:delete 語句後如果不加where條件,所有記錄全部清空
5. 更新表記錄
update 表名 set 字段1=值1,字段2=值2,... where 條件;
注意:必須加where條件
運算符操作
數值比較/字符比較
數值比較:= != > >= < <=
字符比較:= !=
1. 找出攻擊力高於150的英雄的名字和攻擊值
select name,gongji from sanguo where gongji > 150;
2. 將趙雲的攻擊力設置爲360,防禦力設置爲68
update sanguo set gongji=360, fangyu=68 where name='趙雲';
邏輯比較
and(兩個或多個條件同時成立)
or (任意一個條件成立即可)
1. 找出攻擊值高於200的蜀國英雄的名字、攻擊力
select name,gongji from sanguo where gongji > 200 and country = '蜀國';
2. 將吳國英雄中攻擊值爲110的英雄的攻擊值改爲100,防禦力改爲60
update sanguo set gongji = 100, fangyu = 60 where country = '吳國' and gongji = 110;
3. 查找蜀國和魏國的英雄信息
select * from hero where country = '蜀國' or country = '魏國';
範圍內比較
between 值1 and 值2
where 字段名 in(值1,值2,...)
where 字段名 not in(值1,值2,...)
1、查找攻擊值100~200的蜀國英雄信息
select * from sanguo where gongji between 100 and 200 and country = "蜀國";
2、找到蜀國和吳國以外的國家的女英雄信息
select * from sanguo where country not in ("蜀國","吳國") and sex = "女";
3、找到id爲1、3或5的蜀國英雄和貂蟬的信息
select * from sanguo
where id in(1, 3, 5) and country = '蜀國' or name="貂蟬";
select * from sanguo
where (id in(1, 3, 5) and country = '蜀國') or name="貂蟬";用括號來制定優先級
匹配空、非空
空: where name is null
非空: where name is not null
注意:
NULL:空值,只能用is或者is not去匹配
"":空字符串,用=或者!=去匹配
1、姓名爲NULL值的蜀國男英雄信息
select * from sanguo where name is null and country = "蜀國" and sex = "男"
2、姓名爲""的英雄信息
select * from sanguo where name="";
模糊比較
where 字段名 like 表達式
表達式:
1、_:匹配單個字符
2、%:匹配0到多個字符
#NULL不會被統計,只能用is、is not去匹配
1、示例:
select name from sanguo where name like "_%_";
select name from sanguo where name like "%";
select name from sanguo where name like "___";
select name from sanguo where name like "趙%";
SQL查詢
select ...聚合函數 from 表名
where ...
group by ...
having ...
order by ...
limit ...;
order by
作用:給查詢結果進行排序
語法:... order by 字段名 asc/desc
1、將英雄安防禦值從高到低排序
select * from sanguo order by fangyu desc;
2、將蜀國英雄按攻擊值從高到低排序
select * from sanguo where country = "蜀國" order by gongji ASC;
3、將魏蜀兩國英雄中名字爲三個字的防禦值升序排列
select * from sanguo where country in("蜀國","魏國") and name like"___" order by fangyu ASC;
limit 永遠放在SQL語句的最後寫
作用:限制顯示查詢記錄的個數
用法:
1、limit n # 顯示n條記錄
2、limit m,n # m表示從m+1條記錄開始顯示,顯示n條
limit 2,3 顯示第3、4、5三條記錄
3、分頁:每頁顯示5條記錄,顯示4第四頁的內容
第1頁:limit 0,5 # 1 2 3 4 5
第2頁:limit 5,5 # 6 7 8 9 10
第3頁:limit 10,5 # 11 12 13 14 15
第4頁:limit 15,5 # 16 17 18 19 20
每頁顯示n條記錄,顯示第m頁:limit (m-1)*n,n
1、在蜀國英雄中,查找防禦值倒數第二名至倒數第四名的英雄的記錄
select * from sanguo where country = "蜀國" order by fangyu ASC limit 1,3;
2、在蜀國英雄中,查找攻擊值前三名且名字不爲NULL的英雄的姓名、攻擊值和國家
select name,gongji,country from sanguo
where country = "蜀國" and name is not NULL order by gongji ASC limit 3;
聚合函數
avg(字段名):求該字段平均值
sum(字段名):求和
max(字段名):最大值
min(字段名):最小值
count(字段名):統計該字段記錄的個數
1、攻擊力平均值是多少?
select avg(gongji) from sanguo;
2、統計id、name兩個字段分別有幾條記錄?
select count(id),count(name) from sanguo;
# 空值 NULL 不會被統計,""會被統計
3、計算蜀國英雄的總攻擊力
select sum(gongji) from sanguo where country = '蜀國';
4、統計蜀國英雄中攻擊力大於200的英雄
select count(*) from sanguo where gongji>200 and country="蜀國";
# 用*以防NULL不被統計
group by
作用:給查詢結果進行分組(
注意:
1、group by之後的字段名必須要爲select之後的字段名
2、如果select之後的字段名和group by之後的字段不一致,則必須進行聚合處理
1、查詢表中一共有幾個國家
select country from sanguo
group by country;
2、計算每個國家的平均攻擊力
select country,avg(gongji) from sanguo
group by country;
先分組 再聚合 再去重
蜀國
蜀國
蜀國 120 蜀國
魏國
魏國 110 魏國
吳國 115 吳國
3、查找所有國家中英雄的數量最多的前兩名,國家名稱和數量
select country,count(id) from sanguo
group by country
order by count(id) desc
limit 2;
having 語句
作用:對查詢的結果進行進一步篩選
注意:
1、having語句通常和group by語句聯合使用,過濾由group by語句返回的語句集
2、where智能操作表中實際存在的字段,having可操作由聚合函數生成的
1、找出平均攻擊力大於105的國家的前兩名,顯示國家和平均攻擊力
select country,avg(gongji) from sanguo group by country having avg(gongji) > 105 order by avg(gongji) DESC limit 2;
distinct
作用:不顯示字段重複值
注意:
1、distinct和from之間所有字段都相同纔會去重
2、distinct不能對任何字段做聚合處理
1、表中都有哪些國家
select distinct country from sanguo;
2、計算蜀國一共有多少個英雄
select count(distinct id) from sanguo where country = "蜀國";
查詢時做數學運算
運算符
+ - * /
1、查詢時所有英雄攻擊力翻倍
select id,name,gongji*2 as 2gj from sanguo;
約束
作用:保證數據的完整性、一致性、有效性
分類:
1、默認約束(default)
插入記錄不給該字段賦值,則使用默認值
2、非空約束(not null)
不允許該字段值有NULL記錄,否則報錯
create table t2(id int not null, name varchar(15), sex enum("M", "F", "S") default "S");
SQL索引
定義:對數據庫表的一列或多列的值進行排序的一種結構(Btree)
優點:
加快數據檢索速度
缺點:
1、佔用物理存儲空間
2、當對錶中的數據更新時,索引需要動態維護,降低數據維護速度
示例:
查看檢測開啓狀態
show variables like "profiling";
1、開啓運行時間檢測
set profiling=1;
2、執行查詢語句
select name from t1 where name ="lucy99999";
3、查詢看執行時間
show profiles;
4、在name字段創建索引
create index name on t1(name);
5、再執行查詢語句
select name from t1 where name ="lucy88888";
6、查看執行時間
show profiles;
分類:普通索引、唯一索引、主鍵索引、外鍵索引
普通索引(index)
規則:
1、可設置多個字段
2、字段值無約束
3、key標誌:MUL
創建:
1、創建表時
create table t3(id int, name char(15), index(id),index(name));
2、已有表
create index 索引名 on 表名(字段名);
查看索引:
1、desc 表名; key標誌爲:MUL
2、show index from 表名 \G;
刪除索引:
drop index 索引名 on 表名;
唯一索引(unique)
規則:
1、可設置多個字段
2、約束:字段值不允許重複,但可以爲NULL
3、key標誌:UNI
創建:
1、創建表時
unique()
unique()
2、已有表
create unique index ......
查看、刪除同普通索引
主鍵索引(primary key)
自增長屬性(auto_increment,配合主鍵一起使用)
規則:
1、只能有一個主鍵字段
2、約束:不允許重複,且不能爲NULL
3、key標誌:PRI
4、通常設置記錄變好字段id,能唯一鎖定一條記錄
創建:
1、創建表時
create table t4(id int primary key auto_increment, name char(15));
increment默認是1
2、已有表
alter table 表名 add primary key(id);
3、刪除
1、刪除自增長屬性(modify)
alter table 表名 modify id int;
2、刪除主鍵索引
alter table 表名 drop primary key;
數據導入
作用:把文件系統的內容導入到數據庫中
語法:
load data infile "/var/tmp/scoretable.csv"
into table scoretab
fields terminated by ","
lines terminated by "\n";
步驟:
vim /etc/my.cnf
加入secure_file_priv=''
show variables like "%tmpdir%"顯示讀取路徑
1、在數據庫中創建對應的表
create database db3 character set utf8;
create table scoretab( id int, name varchar(15), score float(5,2), number bigint, class char(7));
2、把文件拷貝到數據庫的默認搜索路徑中
show variables like "secure_file_priv";
# 查看默認搜索路徑
拷貝到
3、執行數據導入語句
數據導出
作用:將數據庫中表的記錄導出到系統文件裏
語法:
select ... from 表名
into outfile ""
fields terminated by ","
lines terminated by "\n";
把MOSHOU庫下的sanguo表英雄的姓名、攻擊值、國家導出來,sanguo.txt
select name,gongji,country from MOSHOU.sanguo into outfile "/var/tmp/sanguo.txt" fields terminated by "," lines terminated by "\n"
1、把/etc/passwd 導入到數據庫表userinfo裏面
用戶名 密碼 UID號 GID號 用戶描述 主目錄 登陸權限
2、在userinfo第一列添加一個id字段,主鍵、自增長,顯示寬度爲3,位數不夠用0填充
foreign key 外鍵
定義:讓當前表字段的值在另一個表的範圍內選擇
語法:
foreign key(參考字段名)
references 主表(被參考字段名)
on delete 級聯動作
on update 級聯動作
使用規則:
1、主表、從表字段數據類型要一致
2、主表被參考字段:主鍵
示例:
表1、繳費信息表
id 姓名 班級 繳費金額
1 小張 1班 300
2 小明 1班 250
表2、學生信息表(班主任)
id 姓名 繳費金額
1
步驟
表1
create table jftab(id int primary key, name varchar(15), class char(5), money int);
表2(從表)
create table bjtab(stu_id int, name varchar(15), money int, foreign key(stu_id) references jftab(id) on delete cascade on update cascade);
刪除外鍵:
alter table 表名
drop foreign key 外鍵名;
外鍵名:show create table 表名;來查看
級聯動作
1、cascade
數據級聯三處、更新(參考字段)
2、restrict(默認)
從表有相關聯記錄,不允許主表操作
3、set null
主表刪除、更新,從表相關聯的字段值爲NULL
已有表添加外鍵
alter table 表名 add
foreign key(被參考字段) references 主表(參考字段)
on delete ...
on update ...
表的複製
語法:
create table 表名 select from 表名 where .....;
複製表結構:key屬性不會複製
create table 表名 select * from 表名 where false;
嵌套查詢(子查詢)
定義:把內層的查詢結果作爲外層的查詢條件
語法格式:
select ... from 表名 where 條件 (select ....);
示例:
1、把攻擊值小於平均攻擊值的英雄名字和攻擊值顯示出來
select name,gongji from sanguo where gongji < (select avg(gongji) from sanguo);
2、找出每個國家攻擊力最高的英雄的名字和攻擊值
select name,gongji from sanguo where (country,gongji) in (select country,max(gongji) from sanguo group by country);
多表查詢
1、兩種方式
select 字段名列表 from 表名類表(笛卡爾積)
select * from t1,t2
練習:
1、顯示省和市的詳細信息
select s_name,c_name from sheng,city where sheng.s_id = city.cfather_id;
2、顯示省市縣的詳細信息
select sheng.s_name as sheng, city.c_name as city, xian.x_name as xian from sheng,city,xian where sheng.s_id=city.cfather_id and city.c_id = xian.xfather_id;
連接查詢
1、內鏈接
select 字段名 from 表1 inner join 表2 on 條件;
顯示省和市詳細信息
select sheng.s_name,city.c_name from sheng inner join city on sheng.s_id = city.cfather_id;
顯示省市縣詳細信息
select sheng.s_name,city.c_name,xian.x_name from sheng inner join city on sheng.s_id = city.cfather_id inner join xian on city.c_id=xian.xfather_id;
2、外鏈接
1、左連接
select 字段名 from 表1 left join 表2 on 條件 left join 表3 on 條件;
select sheng.s_name as sheng,city.c_name as city from sheng left join city on sheng.s_id = city.cfather_id;
2、右連接
用法同左連接,只不過是以右表爲主顯示查詢結果
數據備份(mysqldump,在Linux終端中操作)
1、命令格式
mysqldump -u 用戶名 -p 源庫名 > /xxx/xxx.sql
2、源庫名的表達方式
--all-databases 備份所有庫
庫名 備份單個庫
-B 庫1 庫2 庫3 備份多個庫
庫名 表1 表2 表3 備份指定庫的多張表
示例:
1、備份所有庫,放到Backup目錄下:all.sql
mysqldump -u root -p --all-databases > all.sql
2、備份db3庫中的sheng city xian三張表,scx.sql
3、備份MOSHOU和db3庫,md.sql
完全備份
增量備份
數據恢復
1、命令格式
mysql -uroot -p 目標庫名 < /xxx/xxx.sql
2、從所有庫備份中恢復某一個庫(--one-database)
mysql -uroot -p --one-database 目標庫名 < all.sql
目標庫名一定要是原始庫名
注意:
1、恢復庫時如果恢復到原庫會將表中數據覆蓋,新增表不會刪除
2、數據恢復時如果恢復的庫不存在,則必須先創建空庫
MySQL的用戶多賬戶管理
1、開啓MySQL的遠程連接
(Ubuntu)sudo -i cd /etc/mysql/mysqld.conf.d/
打開mysqld.conf
註釋 bind-address=127.0.0.1
重啓服務
2、添加授權用戶
用root用戶登錄到mysql
grant 授權列表 on 庫.表 to "用戶名"@"%" identified by "密碼" with grant option;
最後一句指的是是否有授權權限
權限列表:all privileges,select,insert,*.*(所有庫的所有表)
示例:
1、添加授權用戶haoen110,密碼123,對所有庫所有表所有權限
grant all privileges on *.* to "haoen110"@"%" identified by "123" with grant option;
2、添加授權用戶haoen110,密碼123,對db3庫的所有表所有權限
grant all privileges on db3.* to "haoen110"@"%" identified by "123" with grant option;
3、macOS
create user 'haoen110'@'localhost' identified by '123';
grant all privileges on *.* to "haoen110"@"localhost";
存儲引擎(處理表的處理器)(默認:InnoDB)
基本操作
1、查看所有存儲引擎
show engines;
2、查看已有表的存儲引擎
show create table xxx;
3、更改新的
create table xxx(id int...)engine=muisam,char..;
alter table xxx engine=innodb;
鎖
目的:解決客戶併發訪問的衝突問題
分類
1、讀鎖(共享鎖)
select:加讀鎖之後別人不能更改表記錄,但是可以進行查詢
2、寫鎖(排他鎖、互斥鎖)
insert delete update:加寫鎖之後別人不能查、不能改
鎖粒度
1、表級鎖:myisam
2、行級鎖:innodb
特點
1、InnoDB特點
- 共享表空間
表名.frm:表結構和索引文件
表名.idb:表記錄
- 支持行級鎖
- 支持外鍵、事物操作
1、MyISAM
- 獨享表空間
表名.frm:表結構
表名.myd:表記錄
表名.myi:索引文件
- 支持表級鎖
如何決定使用那個存儲引擎
1、執行查詢操作多的表用MyISAM(使用InnoDB浪費資源)
2、執行寫操作多的表用InnoDB
MySQL調優
1、選擇合適的存儲引擎
讀操作多用MyISAM,寫操作多用InnoDB
2、創建索引
在select、where、order by經常涉及到的字段建立索引
3、SQL語句的優化
1、where子句中不使用 !=,否則放棄索引進行全表掃描
2、儘量避免 NULL 值判斷,否則放棄索引進行全表掃描
優化前:select from t1 where number is null;
優化後:
在number列上設置默認值0,確保number列無NULL值
select from t1 where number=0;
3、儘量避免 or 連接條件,否則放棄索引
優化前:
select id from t1 where id=10 or id=20;
優化後:
select id from t1 where id=10
union all
select id from t1 wehre id= 20;
4、模糊查詢儘量避免使用前值 % ,否則全表掃描
select name from t1 where name like "%c%";
5、儘量避免使用 in 和 not in,否則全表掃描
select id from t1 where id in(1,2,3,4);
select id from t1 where id between 1 and 4;
6、儘量避免使用 select* ..;用具體的字段代替*,不要返回用不到的任何字段
事務和事務回滾
定義:一件事從開始發生到結束的整個過程
作用:確保數據一致性
應用:
1、MySQL中SQL命令會自動commit到數據庫
show variables like "autocommit";
開啓事務
begin;
....
....
....;一條或多條SQL語句
# 此時autocommit被禁用
中止事務
commit;
# 如果沒有成功則使用 rollback;