mysql基礎知識語法匯總整理(二)


mysql基礎知識語法匯總整理(一)

 

insert

/*insert*/
insert into 表名(字段列表) values(值列表);
--蠕蟲復制 (優點:快速復制數據,測試服務器壓力)
insert into 表名1_插入 select (字段列表) from 表名2_復制;
例如:create table copy(
  id int(10) unsigned not null comment 'id',
  name char(20) not null default '' comment '名字'
)engine=InnoDB default charset=utf8 comment='復制表';
insert into copy values(1,'admin_a'),(2,'admin_b'),(3,'admin_c');

create table append(
  id int(10) unsigned not null comment 'id',
  name char(20) not null default '' comment '名字'
)engine=InnoDB default charset=utf8 comment='插入表';
insert into append select * from copy;

--主鍵(唯一索引)重復
insert into 表名(字段列表) values(值列表) on duplicate key update 字段1=值1,字段n=值n;
例如:create table conflict(
  id int(10) unsigned not null primary key comment 'id',
  name char(20) not null default '' comment '名字'
)engine=InnoDB default charset=utf8 comment='沖突表';
insert into conflict values(1,'admin_a');
insert into conflict values(1,'admin_b');--報錯  解決:當主鍵不沖突的時候,相當於一條插入語句;當主鍵有沖突的時候,相當於一條更新語句.

insert into conflict values(1,'admin_b') on duplicate key update name='admin_b';

 

select

/*select*/
select [select選項] *|字段列表 [as 字段別名] from 表名 [where子句][group by子句][having子句][order by子句][limit子句];

--select選項: 系統在查詢到相關數據之后,如何顯示.
--select選項的兩個值:
all: 默認值,保留所有的查詢結果.
distinct: 去重,去掉重復的查詢結果.
例如:create table user(
  id int(10) unsigned not null comment 'id',
  name char(20) not null default '' comment '名字',
  home varchar(50) not null default '' comment '家庭地址'
)engine=InnoDB default charset=utf8 comment='用戶表';
insert into user values(1,'admin_a','gz'),(2,'admin_b','sh'),(3,'admin_c','bj'),(4,'admin_d','sz');
select all * from user;

select distinct * from user;

--關鍵字 as:可以為每個列使用別名. 適用於簡化列標識,避免多個列標識符重復. 也可省略as.
例如:create table score(
  Math int(3) not null default 0 comment '數學',
  English int(3) not null default 0 comment '英語',
  Chinese int(3) not null default 0 comment '語文'
)engine=InnoDB default charset=utf8 comment='成績表';
insert into score values(65,75,85),(75,85,95),(85,95,100);
select Math+English+Chinese from score;

select (Math+English+Chinese) as sum from score;

select (Math+English+Chinese)/3 avg from score;--省略as

--虛擬表的名稱:dual  
--Mysql中執行select語句在適當的時候會自動創建一個虛擬表.
select now() from dual;

--where子句 (條件查詢)
  --從from獲得的數據源中進行查詢
  --整型: 1表示真(返回查詢記錄);0表示假(不返回記錄)
  --表達式由運算符和運算數組成.
  --運算數: 變量(字段)、值、函數返回值
  --比較運算符(常用示例)
    <, >, <=, >=, =, !=<>, IS NULL
    between and | not between and --例如: between A and B; 相當於區間[A,B].
    in | not in --例如:in表示某個值出現; not in表示沒出現在一個集合之中.
    is null | is not null --空值查詢
    like --通配符;  _  :代表任意的單個字符;  % :代表任意的字符
  --邏輯運算符
    &&(AND), ||(OR), !(NOT), XOR異或
例如:create table student(
  id int(10) unsigned not null auto_increment comment 'id',
  name char(10) not null default '' comment '名字',
  score smallint(5) not null default 0 comment '成績',
  class varchar(20) not null default '' comment '班級',
  primary key (id)
)engine=InnoDB default charset=utf8 comment='學生表';
insert into student(name,score,class) values('uzi',100,'A'),('ming',90,'B'),('mlxg',80,'C'),('xiye',95,'A'),('letme',85,'B');
select * from student where id in(1,2,3) and score >95;--查詢ID 1,2,3並且score大於95

select * from student where id between 2 and 5 and  name like 'm%';--查詢ID 區間[2,5]並且模糊查詢name字段以“m”開頭的學生信息

 

select * from student where id in(5) || score >90;--查詢ID 5,或score大於90

--group by子句 (分組)
  --group by 字段/別名 [排序方式]    分組后排序: asc 升序(默認),desc 降序
  --統計函數需配合group by使用:
  count 返回不同的非NULL統計值  count(*)、count(字段)
  sum 求和; max 求最大值; min 求最小值; avg 求平均值
例如:select count(*) as total from student;

select class, sum(score) as sum from student group by class desc;--查詢各個班級總成績,分組班級降序.

select id,class, max(score) as max from student where score>80  group by class;--查詢各個班級最高成績,分數要大於80,分組班級升序.

--having 子句 (條件查詢)
 --where功能、用法相同,執行時機不同.
 --本質區別:where子句是把磁盤上的數據篩選到內存上,而having子句是把內存中的數據再次進行篩選.
 --where不可以使用統計函數. 一般需用統計函數配合group by才會用到having
 例如:select class, min(score) as min from student where min(score)>80 group by class;--報錯
select class, min(score) as min from student group by class having min(score)>80;--查詢各個班級最低成績,分組班級,最低分數大於80

 

--order by子句  (排序)
  --order by 字段1[asc|desc],字段n[asc|desc]
  --排序: asc 升序(默認),desc 降序
例如:insert into student(name,score,class) values('xiaohu',95,'A');--插入相同班級相同分數,要求多字段排序?
select * from student where score >80 order by score,name desc;--查詢score大於80,排序score升序和name降序

--limit 子句  (限制查詢結果數量)
  --limit  offset,length   語法解析: offset是指偏移量,默認為0; length是指需要顯示的記錄數.
  --分頁示例說明: 
    $page = 3; //第三頁
    $pageSize = 10; //頁面顯示10條記錄
    $offset = ($page - 1) * $pageSize; //偏移量為20
    limit $offset,$pageSize //實現分頁 偏移20,顯示10
例如:select * from student where score >60 order by score,name desc limit 1,3;--查詢score大於80,排序score升序和name降序,偏移量為1,顯示3條記錄

 

update

/*update*/
update 表名 set 字段1=值1,字段n=值n [where條件] [order by 字段名 asc|desc] [limit];

 

delete

/*delete*/
delete from 表名 [where條件] [order by 字段名 asc|desc] [limit];

 

聯合查詢

/*聯合查詢 關鍵字:union*/ 
--聯合查詢:就是將多個查詢結果進行縱向上的拼接. (select語句2的查詢結果放在select語句1查詢結果的后面)
--語法:
  select語句1
  union [all | distinct]
  select 語句2
  union [all | distinct]
  select 語句n
例如:查詢A班級最高成績和B班級最低成績? 
(select name, class,score from student where class='A' order by score desc limit 1)
union
(select name, class,score from student where class='B' order by score limit 1);

 

連接查詢

 /*連接查詢*/
 將多個表的字段進行連接,可以指定連接條件.
--交叉連接 cross join
select  *|字段列表 from 表名1 cross join 表名2;

一張表的一條記錄去連接另一張表中的所有記錄,並且保存所有的記錄包含兩個表的所有的字段.
結果上看,就是對兩張表做笛卡爾積,有n1*n2條記錄.
例如:select * from student cross join score;

 

--內連接 inner join
select *|字段列表 from 左表 [inner] join 右表 on 左表.字段 = 右表.字段 [五子句];

數據在左表中存在,同時在右表中又有對應的匹配的結果才會被保存. 如果沒有匹配上,數據沒有意義不會保存.
通常就是兩張表中存在相同的某個字段.(項目中通常是關聯主鍵ID) using() 用法連接兩表公共字段. 例如:using(ID)
例如:create table teacher(
  id int(10) unsigned not null auto_increment comment 'id',
  name char(10) not null default '' comment '名字',
  class varchar(20) not null default '' comment '班級',
  primary key (id)
)engine=InnoDB default charset=utf8 comment='教師班級';
insert into teacher(name,class) values('niuPai','A'),('feng','B');
select student.*, teacher.class as t_class, teacher.name as t_name from student join teacher on student.class = teacher.class;

--外連接外 outer join
如果數據不存在,也會出現在連接結果中.
  -- 左外連接 left join
  select *|字段列表 from 左表 left [outer] join 右表 on 左表.字段 = 右表.字段 [五子句];
  如果數據不存在,左表記錄會出現,而右表為null填充
  例如:select student.*, teacher.class as t_class, teacher.name as t_name from student left join teacher on student.class = teacher.class;

  -- 右外連接 right join
  select *|字段列表 from 右表 right [outer] join 左表 on 右表.字段 = 左表.字段 [五子句];
  如果數據不存在,右表記錄會出現,而左表為null填充
--自然連接 natural join
自動判斷連接條件完成連接.
  --自然內連接 natural inner join
  select *|字段列表 from 左表 natural [inner] join 右表;
  自然內連接其實就是內連接,這里的匹配條件是由系統自動指定.

  --自然外連接 natural outer join
  自然外連接分為自然左外連接和自然右外連接.匹配條件也是由系統自動指定.

  --自然左外連接 natural left join
  select *|字段列表 from 左表 natural left [outer] join 右表;
  
  --自然右外連接 natural right join
  select *|字段列表 from 右表 natural right [outer] join 左表;
注意:項目中使用最多是內連接和外連接.

 

子查詢

/*子查詢*/
子查詢(內查詢)在主查詢(外查詢)之前一次執行完成,子查詢的結果被主查詢使用.
使用子查詢需用括號包裹.
例如:insert into student(name,score,class) values('rookie',100,'C');
select * from student where score=(select max(score) as max from student);--查詢班級最高成績學生的記錄

根據子查詢返回值的形式:
1.單一值: 返回單行單列的子查詢,也叫標量子查詢.
例如:select max(score) as max from student;

2.一列: 返回單列的子查詢,也叫列子查詢.
例如:select name from student;

3.一行: 返回一行的子查詢,也加行子查詢.
select *|字段列表 from 表名 where(字段1,字段n)=(行子查詢結果)
例如:select * from student where score=(select min(score) as min from student);--查詢班級最低成績學生的記錄

4.多行多列: 返回多行多列的子查詢,也叫表子查詢.
例如:select * from student where class in ('B','C') order by score;--查詢B班和C班,排序score字段升序

--exists
--主要作用就是判斷后面的select語句有沒有查詢到數據.結果為true有返回數據,否則就是false.
例如:select exists (select * from student where name ='uzi');--有

select exists (select * from student where name ='admin');--無

 

視圖

/*視圖*/
視圖是一張虛擬表,它表示一張表的部分數據和多張表的綜合數據,視圖的結構和數據都是建立在基表上.
視圖僅僅是一個表結構,視圖的數據並不在數據庫中存儲,數據保存在基表中. 一張表可以創建多個視圖.
-- 視圖作用
簡化業務邏輯,對客戶端隱藏真實的表結構
--創建視圖
create [algorithm = undefined | merge | temptable] view 視圖名稱 [(字段列表)]
as
sql語句

語法解析:
1.視圖名必須唯一,同時不能與表重名.
2.指定視圖執行的算法,通過algorithm指定.
3.merge: 合並算法,將視圖的語句和外層的語句合並后再執行.
4.temptable: 臨時表算法,將視圖執行的結果生成一張臨時表,再執行外層語句.
5.undefined: 未定義型,用哪種算法有MySQL決定,默認算法merge.
6."字段列表"如果存在,數目必須等於select語句檢索的列數
例如:create view v_student (v_name,v_score)
as
select name,score from student where score >80;

--查看結構
show create view 視圖名稱

--刪除視圖
drop view [if exists] 視圖名稱
注意: 刪除視圖后,數據庫中的數據依然存在.(對當前視圖刪除)

--修改視圖結構 
alter view 視圖名稱 [(字段列表)]
as
sql語句

 

事物

/*事物*/
事物:是並發控制的基本單位.事務就是一系列的操作,這些操作要么都執行,要么都不執行.(事務中可以保存多個SQL語句. 這些SQL語句是一個整體. 要么都執行,要么都不執行.)

--事務操作
  --開啟事務
  start transaction; 或者 begin;
  --提交事務
  commit;
  --回滾事務
  rollback;

注意: 修改事務自動提交  set autocommit = 0 | 1  (0:取消自動提交;1:自動提交)--設置為不自動提交,因為Mysql默認自動提交執行
查看:show variables like 'autocommit';

例如:create table goods(
  id int(10) unsigned not null auto_increment comment 'id',
  goods_name char(10) not null default '' comment '商品名',
  price int(5) not null default '0' comment '價格',
  primary key (id)
)engine=InnoDB default charset=utf8 comment='商品表';
start transaction;--開啟事物

insert into goods(goods_name,price) values('milk','43');
insert into goods(goods_name,price) values('bread','15');

commit;--提交事物

begin;--開啟事物

insert into goods(goods_name,price) values('book','99');

rollback;--回滾事物

-- 事務的特性
1. 原子性: 事務是一個不可分割的工作單位,事務中的操作要么都執行,要么都不執行.
2. 一致性: 事務前后數據的完整性必須保持一致. (事務開始和結束時,外部數據一致. 在整個事務過程中,操作是連續的.)
3. 隔離性: 多個用戶並發訪問數據庫時,一個用戶的事務不能被其它用戶的事物所干擾,多個並發事務之間的數據要相互隔離.
4. 持久性: 一個事務一旦被提交,它對數據庫中的數據改變就是永久性的.

-- 事務的原理
利用InnoDB的自動提交(autocommit)特性完成. 普通的Mysql執行語句后,當前的數據提交操作均可被其它客戶端可見. 
事務是暫時關閉“自動提交”機制,需要commit提交持久化數據操作.

-- 注意
1. 數據定義語言(DDL)語句不能被回滾. 比如創建或取消數據庫的語句; 創建、取消或更改表或存儲的子程序的語句.
2. 事務不能被嵌套

 

用戶權限管理

/*用戶權限管理*/
用戶信息表:mysql數據庫的下, user表中
--創建用戶
create user 用戶名[@主機地址] identified by '密碼';

例如:create user 'user_one'@'localhost' identified by '1234';--創建一個只能本機訪問的用戶
create user 'user_two'@'192.168.1.204.%' identified by '1234';--創建一個可以局域網訪問的用戶
create user 'user_three' identified by '1234';--創建一個可全網訪問的用戶
select host,user,password from user;--查看user表,host用戶名和密碼

--重命名用戶
rename user 老用戶名[@老主機地址] to 新用戶名[@新主機地址];

-- 設置密碼
set password = password('修改密碼'); -- 為當前用戶設置密碼
set password for 用戶名 = password('修改密碼'); -- 為指定用戶設置密碼
例如:set password for 'user_three' = password('123456789'); -- 指定'user_three'用戶設置密碼

-- 刪除用戶
drop user 用戶名[@主機地址];
例如:drop user 'user_two'@'192.168.1.204.%';

--分配權限給用戶
grant 權限列表 on  *|庫名 . *|表名  to 用戶名[@主機地址] [identified by "用戶密碼"] [with grant option];

語法解析:
權限列表: all [privileges]: 表示所有權限; delete:允許使用delete; select:允許使用select; update:允許使用update; insert:允許使用insert 等...
 *.* :表示所有庫的所有表
庫名.表名 :表示某庫下面的某表
例如: grant update,insert on *.* to user_one@'localhost' identified by "1234" with grant option;

--刷新權限
flush privileges;

--查看權限
show grants for 用戶名[@主機地址];  
show grants for 'user_one'@'localhost';

--查看當前用戶權限
show grants;

--撤消權限
revoke 權限列表 on *|庫名 . *|表名 from 用戶名[@主機地址];
revoke all privileges, grant option from 用戶名[@主機地址];-- 撤銷所有權限
例如:revoke update on *.* from 'user_one'@'localhost';

 

mysql基礎知識語法匯總整理(一)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM