MySql資料庫基本介紹和基本文法
一、資料庫簡單介紹
1、 按照資料庫的發展時間順序,主要出現了以下類型資料庫系統:
Ø 網狀型資料庫
Ø 層次型資料庫
Ø 關系型資料庫
Ø 面向對象資料庫
上面4中資料庫系統中,關系型資料庫使用最為廣泛。面向對象資料庫則是由面向對象語言催生的新型資料庫,目前的一些資料庫系統,如:SQL Server 2005、Oracle10g等都開始增加面向對象的特性。
二、常用基本SQL語句/文法
Ø SQL語句基礎理論
SQL是操作和檢索關系型資料庫的标準語言,标準SQL語句可用于操作然後關系型資料庫。
标準的SQL語句通常劃分為以下類型:
查詢語句:主要由于select關鍵字完成,查詢語句是SQL語句中最複雜,功能最豐富的語句。
DML(Data Munipulation Language,資料操作語言)語句,這組DML語句修改後資料将保持較好的一緻性;操作表的語句,如插入、修改、删除等;
DDL(Data Definition Language,資料定義語言)語句,操作資料對象的語言,有create、alter、drop。
DCL(Data Control Language,資料控制語言)語句,主要有grant、revoke語句。
事務控制語句:主要有commit、rollback和savepoint三個關鍵字完成
DDL語句
DDL語句是操作資料庫對象的語句,包括建立create、删除drop、修改alter資料庫對象。
常見資料庫對象
對象名稱 | 對應關鍵字 | 描述 |
表 | table | 表是資料庫存儲的邏輯單元,以行和列的形式存在;列是字段,行就是一條資料記錄 |
資料字典 | 就是系統表,存儲資料庫相關資訊的表,系統表裡的資料通常有資料庫系統維護。系統表結構和資料,開發人員不應該手動修改,隻能查詢其中的資料 | |
視圖 | view | 一個或多個資料表裡的資料的邏輯顯示,視圖就是一張虛拟的表,并不真正存儲資料 |
限制 | constraint | 執行資料檢驗規則,用于保證資料完整性的規則 |
索引 | index | 用于提高查詢性能,相當于書的目錄 |
函數 | function | 用于完成一個特定的計算,具有傳回值和參數 |
存儲過程 | procedure | 完成某項完整的業務處理,沒有傳回值,但可通過傳出參數将多個值傳個調用環境 |
觸發器 | trigger | 相當于一個事件的監聽器,當資料庫發生特定的事件後,觸發器被觸發,完成響應處理 |
上面的對象都可以通過用create、alter、drop完成相關的建立、修改、删除操作。
常用資料類型
列類型 | 說明 |
tinyint/smallint/mediumint int(integer)/bigint | 1位元組、2位元組、3位元組、4位元組、8位元組整數,又可分有符号和無符号兩種。這些整數類型的差別僅僅表現範圍不同 |
float/double | 單精度、雙精度浮點類型 |
decimal(dec) | 精确小數類型,相當于float和double不會産生精度丢失問題 |
date | 日期類型,不能儲存時間。當Java裡的Date對象儲存到該類型中,時間部分丢失 |
time | 時間類型,不能儲存日期。當Java的Date對象的儲存在該類型中,日期部分丢失 |
datetime | 日期、時間類型 |
timestamp | 時間戳類型 |
year | 年類型,僅儲存年份 |
char | 定長字元串類型 |
varchar | 可變長度字元串類型 |
binary | 定長二進制字元串類型,它以二進制形式儲存字元串 |
varbinary | 可變長度的二進制字元串類型,二進制形式儲存字元串 |
tingblob/blob mediumblob/longblob | 1位元組、2位元組、3位元組、4位元組的二進制大對象,可存存儲超圖檔、音樂等二進制資料,分别可存儲:255/64K/16M/4G的大小 |
tingtext/text mediumtext/longtext | 1位元組、2位元組、3位元組、4位元組的文本對象,可存儲超長長度的字元串,分别可存儲:255/64K/16M/4G的大小的文本 |
enum(‘val1’, ‘val2’, …) | 枚舉類型,該列的值隻能是enum括号中出現的值的之一 |
set(‘value1’, ‘value2’, …) | 集合類型,該列的值可以是set中的一個或多個值 |
Ø 常用查詢
MySQL結束符是“;”結束。
1、 顯示所有資料庫
show databases;
2、 删除資料庫
drop database dbName;
3、 建立資料庫
create database [if not exists] dbName;
中括号部分可選的,判斷該資料不存在就建立
4、 切換、使用指定資料庫
use dbName;
5、 顯示目前使用資料庫所有的表對象
show tables;
6、 顯示表結構describe(desc)
desc tableName;
7、 建立一張表
create table user (
--int 整型
uId int,
--小數
uPrice decimal,
--普通長度文本,default設定預設值
uName varchar(255) default ‘zhangsan’,
--超長文本
uRemark text,
--圖檔
uPhoto blob,
--日期
uBirthday datetime
);
8、 子查詢建表方法
部分列名比對模式:
create table userInfo (
name varchar(20),
sex char
)
as
select name, sex from user;
上面的列名和子查詢的列名以及類型要對應
全部列名模式:
create table userInfo
as
select * from user;
直接将整個表的類型和資料備份到新表userInfo中
9、 添加表字段
添加單列
alter table user add tel varchar(11) default ‘02012345678’;
添加多列
alter table user
add (
photo blob,
birthday date
);
上面就同時增加了多列字段
10、 修改表字段
修改tel列
alter table user modify tel varchar(15) default ‘02087654321’;
修改tel列的位置,在第一列顯示
alter table user modify tel varchar(15) default \'02087654321\' first;
修改tel列的位置,在指定列之後顯示
alter table user modify tel varchar(15) default \'02087654321\' after age;
注意:alter modify不支援一次修改多個列,但是Oracle支援多列修改
但是MySQL可以通過多個modify的方式完成:
alter table user
modify tel varchar(15) default \'02087654321\' first,
modify name varchar(20) after tel;
11、 删除指定字段
alter table user drop photo;
12、 重命名表資料
表重命名
alter table user rename to users;
字段重命名
alter table users change name u_name varchar(10);
alter table users change sex u_sex varchar(10) after u_name;
如果需要改變列名建議使用change,如果需要改變資料類型和顯示位置可以使用modify
13、 删除表
drop table users;
drop删除表會删除表結構,表對象将不存在資料中;資料也不會存在;表内的對象也不存在,如:索引、視圖、限制;
truncate删除表
truncate都被當成DDL出來,truncate的作用就是删除該表裡的全部資料,保留表結構。相當于DDL中的delete語句,
但是truncate比delete語句的速度要快得多。但是truncate不能帶條件删除指定資料,隻會删除所有的資料。如果删除的表有外鍵,
删除的速度類似于delete。但新版本的MySQL中truncate的速度比delete速度快。
Ø 限制
MySQL中限制儲存在information_schema資料庫的table_constraints中,可以通過該表查詢限制資訊;
限制主要完成對資料的檢驗,保證資料庫資料的完整性;如果有互相依賴資料,保證該資料不被删除。
常用五類限制:
not null:非空限制,指定某列不為空
unique: 唯一限制,指定某列和幾列組合的資料不能重複
primary key:主鍵限制,指定某列的資料不能重複、唯一
foreign key:外鍵,指定該列記錄屬于主表中的一條記錄,參照另一條資料
check:檢查,指定一個表達式,用于檢驗指定資料
MySQL不支援check限制,但可以使用check限制,而沒有任何效果;
根據限制資料列限制,限制可分為:
單列限制:每個限制隻限制一列
多列限制:每個限制限制多列資料
MySQL中限制儲存在information_schema資料庫的table_constraints中,可以通過該表查詢限制資訊;
1、 not null限制
非空限制用于確定目前列的值不為空值,非空限制隻能出現在表對象的列上。
Null類型特征:
所有的類型的值都可以是null,包括int、float等資料類型
空字元串“”是不等于null,0也不等于null
create table temp(
id int not null,
name varchar(255) not null default ‘abc’,
sex char null
)
上面的table加上了非空限制,也可以用alter來修改或增加非空限制
增加非空限制
alter table temp
modify sex varchar(2) not null;
取消非空限制
alter table temp modify sex varchar(2) null;
取消非空限制,增加預設值
alter table temp modify sex varchar(2) default ‘abc’ null;
2、 unique
唯一限制是指定table的列或列組合不能重複,保證資料的唯一性。雖然唯一限制不允許出現重複的值,但是可以為多個null
同一個表可以有多個唯一限制,多個列組合的限制。在建立唯一限制的時候,如果不給唯一限制名稱,就預設和列名相同。
唯一限制不僅可以在一個表内建立,而且可以同時多表建立組合唯一限制。
MySQL會給唯一限制的列上預設建立一個唯一索引;
create table temp (
id int not null,
name varchar(25),
password varchar(16),
--使用表級限制文法,
constraint uk_name_pwd unique(name, password)
);
表示使用者名和密碼組合不能重複
添加唯一限制
alter table temp add unique(name, password);
alter table temp modify name varchar(25) unique;
删除限制
alter table temp drop index name;
3、 primary key
主鍵限制相當于唯一限制+非空限制的組合,主鍵限制列不允許重複,也不允許出現空值;如果的多列組合的主鍵限制,
那麼這些列都不允許為空值,并且組合的值不允許重複。
每個表最多隻允許一個主鍵,建立主鍵限制可以在列級别建立,也可以在表級别上建立。MySQL的主鍵名總是PRIMARY,
當建立主鍵限制時,系統預設會在所在的列和列組合上建立對應的唯一索引。
列模式:
create table temp(
/*主鍵限制*/
id int primary key,
name varchar(25)
);
create table temp2(
id int not null,
name varchar(25),
pwd varchar(15),
constraint pk_temp_id primary key(id)
);
組合模式:
create table temp2(
id int not null,
name varchar(25),
pwd varchar(15),
constraint pk_temp_id primary key(name, pwd)
);
alter删除主鍵限制
alter table temp drop primary key;
alter添加主鍵
alter table temp add primary key(name, pwd);
alter修改列為主鍵
alter table temp modify id int primary key;
設定主鍵自增
create table temp(
id int auto_increment primary key,
name varchar(20),
pwd varchar(16)
);
auto_increment自增模式,設定自增後在插入資料的時候就不需要給該列插入值了。
4、 foreign key 限制
外鍵限制是保證一個或兩個表之間的參照完整性,外鍵是建構于一個表的兩個字段或是兩個表的兩個字段之間的參照關系。
也就是說從表的外鍵值必須在主表中能找到或者為空。
當主表的記錄被從表參照時,主表的記錄将不允許删除,如果要删除資料,需要先删除從表中依賴該記錄的資料,
然後才可以删除主表的資料。還有一種就是級聯删除子表資料。
注意:外鍵限制的參照列,在主表中引用的隻能是主鍵或唯一鍵限制的列,假定引用的主表列不是唯一的記錄,
那麼從表引用的資料就不确定記錄的位置。同一個表可以有多個外鍵限制。
建立外鍵限制:
主表
create table classes(
id int auto_increment primary key,
name varchar(20)
);
從表
create table student(
id int auto_increment,
name varchar(22),
constraint pk_id primary key(id),
classes_id int references classes(id)
);
通常先建主表,然後再建從表,這樣從表的參照引用的表才存在。
表級别建立外鍵限制:
create table student(
id int auto_increment primary key,
name varchar(25),
classes_id int,
foreign key(classes_id) references classes(id)
);
上面的建立外鍵的方法沒有指定限制名稱,系統會預設給外鍵限制配置設定外鍵限制名稱,命名為student_ibfk_n,
其中student是表名,n是目前限制從1開始的整數。
指定限制名稱:
create table student(
id int auto_increment primary key,
name varchar(25),
classes_id int,
/*指定限制名稱*/
constraint fk_classes_id foreign key(classes_id) references classes(id)
);
多列外鍵組合,必須用表級别限制文法:
create table classes(
id int,
name varchar(20),
number int,
primary key(name, number)
);
create table student(
id int auto_increment primary key,
name varchar(20),
classes_name varchar(20),
classes_number int,
/*表級别聯合外鍵*/
foreign key(classes_name, classes_number) references classes(name, number)
);
删除外鍵限制:
alter table student drop foreign key student_ibfk_1;
alter table student drop foreign key fk_student_id;
增加外鍵限制
alter table student add foreign key(classes_name, classes_number) referencesclasses(name, number);
自引用、自關聯(遞歸表、樹狀表)
create table tree(
id int auto_increment primary key,
name varchar(50),
parent_id int,
foreign key(parent_id) references tree(id)
);
級聯删除:删除主表的資料時,關聯的從表資料也删除,則需要在建立外鍵限制的後面增加on deletecascade
或on delete set null,前者是級聯删除,後者是将從表的關聯列的值設定為null。
create table student(
id int auto_increment primary key,
name varchar(20),
classes_name varchar(20),
classes_number int,
/*表級别聯合外鍵*/
foreign key(classes_name, classes_number) references classes(name, number) on deletecascade
);
5、 check限制
MySQL可以使用check限制,但check限制對資料驗證沒有任何作用。
create table temp(
id int auto_increment,
name varchar(20),
age int,
primary key(id),
/*check限制*/
check(age > 20)
);
上面check限制要求age必須大于0,但沒有任何作用。但是建立table的時候沒有任何錯誤或警告。
Ø 索引
索引是存放在模式(schema)中的一個資料庫對象,索引的作用就是提高對表的檢索查詢速度,
索引是通過快速通路的方法來進行快速定位資料,進而減少了對磁盤的讀寫操作。
索引是資料庫的一個對象,它不能獨立存在,必須對某個表對象進行依賴。
提示:索引儲存在information_schema資料庫裡的STATISTICS表中。
建立索引方式:
自動:當表上定義主鍵限制、唯一、外鍵限制時,該表會被系統自動添加上索引。
手動:手動在相關表或列上增加索引,提高查詢速度。
删除索引方式:
自動:當表對象被删除時,該表上的索引自動被删除
手動:手動删除指定表對象的相關列上的索引
索引類似于書籍的目錄,可以快速定位到相關的資料,一個表可以有多個索引。
建立索引:
create index idx_temp_name on temp(name);
組合索引:
create index idx_temp_name$pwd on temp(name, pwd);
删除索引:
drop index idx_temp_name on temp;
Ø 視圖
視圖就是一個表或多個表的查詢結果,它是一張虛拟的表,因為它并不能存儲資料。
視圖的作用、優點:
限制對資料的通路
讓複雜查詢變得簡單
提供資料的獨立性
可以完成對相同資料的不同顯示
建立、修改視圖
create or replace view view_temp
as
select name, age from temp;
通常我們并不對視圖的資料做修改操作,因為視圖是一張虛拟的表,它并不存儲實際資料。如果想讓視圖不被修改,可以用with check option來完成限制。
create or replace view view_temp
as
select * from temp
with check option;
修改視圖:
alter view view_temp
as
select id, name from temp;
删除視圖:
drop view view_temp;
顯示建立文法:
show create view v_temp;
Ø DML語句
DML主要針對資料庫表對象的資料而言的,一般DML完成:
插入新資料
修改已添加的資料
删除不需要的資料
1、 insert into 插入語句
insert into temp values(null, ‘jack’, 25);
主鍵自增可以不插入,是以用null代替
指定列
insert into temp(name, age) values(‘jack’, 22);
在表面後面帶括号,括号中寫列名,values中寫指定列名的值即可。當省略列名就表示插入全部資料,
注意插入值的順序和列的順序需要保持一緻。
Set方式插入,也可以指定列
insert into temp set id = 7, name = \'jason\';
MySQL中外鍵的table的外鍵引用列可以插入資料可以為null,不參照主表的資料。
使用子查詢插入資料
insert into temp(name) select name from classes;
多行插入
insert into temp values(null, ‘jack’, 22), (null, ‘jackson’ 23);
2、 update 修改語句
update主要完成對資料的修改操作,可以修改一條或多條資料。修改多條或指定條件的資料,需要用where條件來完成。
修改所有資料
update temp set name = ‘jack2’;
所有的資料的name會被修改,如果修改多列用“,”分開
update temp set name = ‘jack’, age = 22;
修改指定條件的記錄需要用where
update temp set name = ‘jack’ where age > 22;
3、 delete 删除語句
删除table中的資料,可以删除所有,帶條件可以删除指定的記錄。
删除所有資料
delete from temp;
删除指定條件資料
delete from temp where age > 20;
Ø select 查詢、function 函數
select查詢語句用得最廣泛、功能也最豐富。可以完成單條記錄、多條記錄、單表、多表、子查詢等。
1、 查詢某張表所有資料
select * from temp;
*代表所有列,temp代表表名,不帶條件就查詢所有資料
2、 查詢指定列和條件的資料
select name, age from temp where age = 22;
查詢name和age這兩列,age 等于22的資料。
3、 對查詢的資料進行運算操作
select age + 2, age / 2, age – 2, age * 2 from temp where age – 2 > 22;
4、 concat函數,字元串連接配接
select concat(name, ‘-eco’) from temp;
concat和null進行連接配接,會導緻連接配接後的資料成為null
5、 as 對列重命名
select name as ‘名稱’ from temp;
as也可以省略不寫,效果一樣
如果重命名的列名出現特殊字元,如“‘”單引号,那就需要用雙引号引在外面
select name as “名’稱” from temp;
6、 也可以給table去别名
select t.name Name from temp as t;
7、 查詢常量
類似于SQL Server
select 5 + 2;
select concat(\'a\', \'bbb\');
8、 distinct 去掉重複資料
select distinct id from temp;
多列将是組合的重複資料
select distinct id, age from temp;
9、 where 條件查詢
大于>、大于等于>=、小于<、小于等于<=、等于=、不等于<>
都可以出現在where語句中
select * from t where a > 2 or a >= 3 or a < 5 or a <= 6 or a = 7 or a <> 0;
10、 and 并且
select * from temp where age > 20 and name = ‘jack’;
查詢名稱等于jack并且年齡大于20的
11、 or 或者
滿足一個即可
select * from tmep where name = ‘jack’ or name = ‘jackson’;
12、 between v and v2
大于等于v且小于等于v2
select * form temp where age between 20 and 25;
13、 in 查詢
可以多個條件 類似于or
select * from temp where id in (1, 2, 3);
查詢id在括号中出現的資料
14、 like 模糊查詢
查詢name以j開頭的
select * from temp where name like ‘j%’;
查詢name包含k的
select * from temp where name like ‘%k%’;
escape轉義
select * from temp where name like ‘/_%’ escape ‘/’;
指定/為轉義字元,上面的就可以查詢name中包含“_”的資料
15、 is null、is not null
查詢為null的資料
select * from temp where name is null;
查詢不為null的資料
select * from temp where name is not null;
16、 not
select * from temp where not (age > 20);
取小于等于20的資料
select * from temp where id not in(1, 2);
17、 order by
排序,有desc、asc升序、降序
select * from temp order by id;
預設desc排序
select * from temp order by id asc;
多列組合
select * from temp order by id, age;
Ø function 函數
函數的作用比較大,一般多用在select查詢語句和where條件語句之後。按照函數傳回的結果,
可以分為:多行函數和單行函數;所謂的單行函數就是将每條資料進行獨立的計算,然後每條資料得到一條結果。
如:字元串函數;而多行函數,就是多條記錄同時計算,得到最終隻有一條結果記錄。如:sum、avg等
多行函數也稱為聚集函數、分組函數,主要用于完成一些統計功能。MySQL的單行函數有如下特征:
單行函數的參數可以是變量、常量或資料列。單行函數可以接受多個參數,但傳回一個值。
單行函數就是它會對每一行單獨起作用,每一行(可能包含多個參數)傳回一個結果。
單行函數可以改變參數的資料類型。單行函數支援嵌套使用:内層函數的傳回值是外層函數的參數。
單行函數可以分為:
類型轉換函數;
位函數;
流程控制語句;
加密解密函數;
資訊函數
單行函數
1、 char_length字元長度
select char_length(tel) from user;
2、 sin函數
select sin(age) from user;
select sin(1.57);
3、 添加日期函數
select date_add(\'2010-06-21\', interval 2 month);
interval是一個關鍵字,2 month是2個月的意思,2是數值,month是機關
select addDate(\'2011-05-28\', 2);
在前面的日期上加上後面的天數
4、 擷取目前系統時間、日期
select curdate();
select curtime();
5、 加密函數
select md5(\'zhangsan\');
6、 Null 處理函數
select ifnull(birthday, \'is null birthday\') from user;
如果birthday為null,就傳回後面的字元串
select nullif(age, 245) from user;
如果age等于245就傳回null,不等就傳回age
select isnull(birthday) from user;
判斷birthday是否為null
select if(isnull(birthday), \'birthday is null\', \'birthday not is null\') from user;
如果birthday為null或是0就傳回birthday is null,否則就傳回birthday not is null;類似于三目運算符
7、 case 流程函數
case函數是一個流程控制函數,可以接受多個參數,但最終隻會傳回一個結果。
select name,
age,
(case sex
when 1 then \'男\'
when 0 then \'女\'
else \'火星人\'
end
) sex
from user;
組函數
組函數就是多行函數,組函數是完成一行或多行結果集的運算,最後傳回一個結果,而不是每條記錄傳回一個結果。
1、 avg平均值運算
select avg(age) from user;
select avg(distinct age) from user;
2、 count 記錄條數統計
select count(*), count(age), count(distinct age) from user;
3、 max 最大值
select max(age), max(distinct age) from user;
4、 min 最小值
select min(age), min(distinct age) from user;
5、 sum 求和、聚和
select sum(age), sum(distinct age) from user;
select sum(ifnull(age, 0)) from user;
6、 group by 分組
select count(*), sex from user group by sex;
select count(*) from user group by age;
select * from user group by sex, age;
7、 having進行條件過濾
不能在where子句中過濾組,where子句僅用于過濾行。過濾group by需要having
不能在where子句中用組函數,having中才能用組函數
select count(*) from user group by sex having sex <> 2;
Ø 多表查詢和子查詢
資料庫的查詢功能最為豐富,很多時候需要用到查詢完成一些事物,而且不是單純的對一個表進行操作。而是對多個表進行聯合查詢,
MySQL中多表連接配接查詢有兩種規範,較早的SQL92規範支援,如下幾種表連接配接查詢:
等值連接配接
非等值連接配接
外連接配接
廣義笛卡爾積
SQL99規則提供了可讀性更好的多表連接配接文法,并提供了更多類型的連接配接查詢,SQL99支援如下幾種多表連接配接查詢:
交叉連接配接
自然連接配接
使用using子句的連接配接
使用on子句連接配接
全部連接配接或者左右外連接配接
SQL92的連接配接查詢
SQL92的連接配接查詢文法比較簡單,多将多個table放置在from關鍵字之後,多個table用“,”隔開;
連接配接的條件放在where條件之後,與查詢條件直接用and邏輯運算符進行連接配接。如果條件中使用的是相等,
則稱為等值連接配接,相反則稱為非等值,如果沒有任何條件則稱為廣義笛卡爾積。
廣義笛卡爾積:select s.*, c.* from student s, classes c;
等值:select s.*, c.* from student s, classes c where s.cid = c.id;
非等值:select s.*, c.* from student s, classes c where s.cid <> c.id;
select s.*, c.name classes from classes c, student s where c.id = s.classes_id ands.name is not null;
SQL99連接配接查詢
1、交叉連接配接cross join,類似于SQL92的笛卡爾積查詢,無需條件。如:
select s.*, c.name from student s cross join classes c;
2、自然連接配接 natural join查詢,無需條件,預設條件是将2個table中的相同字段作為連接配接條件,如果沒有相同字段,查詢的結果就是空。
select s.*, c.name from student s natural join classes c;
3、using子句連接配接查詢:using的子句可以是一列或多列,顯示的指定兩個表中同名列作為連接配接條件。
如果用natural join的連接配接查詢,會把所有的相同字段作為連接配接查詢。而using可以指定相同列及個數。
select s.*, c.name from student s join classes c using(id);
4、 join … on連接配接查詢,查詢條件在on中完成,每個on語句隻能指定一個條件。
select s.*, c.name from student s join classes c on s.classes_id = c.id;
5、 左右外連接配接:3種外連接配接,left [outer] join、right [outer] join,連接配接條件都是通過用on子句來指定,條件可以等值、非等值。
select s.*, c.name from student s left join classes c on s.classes_id = c.id;
select s.*, c.name from student s right join classes c on s.classes_id = c.id;
子查詢
子查詢就是指在查詢語句中嵌套另一個查詢,子查詢可以支援多層嵌套。子查詢可以出現在2個位置:
from關鍵字之後,被當做一個表來進行查詢,這種用法被稱為行内視圖,因為該子查詢的實質就是一個臨時視圖
出現在where條件之後作為過濾條件的值
子查詢注意點:
子查詢用括号括起來,特别情況下需要起一個臨時名稱
子查詢當做臨時表時(在from之後的子查詢),可以為該子查詢起别名,尤其是要作為字首來限定資料列名時
子查詢用作過濾條件時,将子查詢放在比較運算符的右邊,提供可讀性
子查詢作為過濾條件時,單行子查詢使用單行運算符,多行子查詢用多行運算符
将from後面的子查詢當做一個table來用:
select * from (select id, name from classes) s where s.id in (1, 2);
當做條件來用:
select * from student s where s.classes_id in (select id from classes);
select * from student s where s.classes_id = any (select id from classes);
select * from student s where s.classes_id > any (select id from classes);
Ø 操作符和函數
1、 boolean隻判斷
select 1 is true, 0 is false, null is unknown;
select 1 is not unknown, 0 is not unknown, null is not unknown;
2、 coalesce函數,傳回第一個非null的值
select coalesce(null, 1);
select coalesce(1, 1);
select coalesce(null, 1);
select coalesce(null, null);
3、 當有2個或多個參數時,傳回最大的那個參數值
select greatest(2, 3);
select greatest(2, 3, 1, 9, 55, 23);
select greatest(\'D\', \'A\', \'B\');
4、 Least函數,傳回最小值,如果有null就傳回null值
select least(2, 0);
select least(2, 0, null);
select least(2, 10, 22.2, 35.1, 1.1);
5、 控制流函數
select case 1 when 1 then \'is 1\' when 2 then \'is 2\' else \'none\' end;
select case when 1 > 2 then \'yes\' else \'no\' end;
6、 ascii字元串函數
select ascii(\'A\');
select ascii(\'1\');
7、 二進制函數
select bin(22);
8、 傳回二進制字元串長度
select bit_length(11);
9、 char将值轉換成字元,小數取整四舍五入
select char(65);
select char(65.4);
select char(65.5);
select char(65.6);
select char(65, 66, 67.4, 68.5, 69.6, \'55.5\', \'97.3\');
10、 using改變字元集
select charset(char(0*65)), charset(char(0*65 using utf8));
11、 得到字元長度char_length,character_length
select char_length(\'abc\');
select character_length(\'eft\');
12、 compress壓縮字元串、uncompress解壓縮
select compress(\'abcedf\');
select uncompress(compress(\'abcedf\'));
13、 concat_ws分隔字元串
select concat_ws(\'#\', \'first\', \'second\', \'last\');
select concat_ws(\'#\', \'first\', \'second\', null, \'last\');
Ø 事務處理
動作
開始事務:start transaction
送出事務:commit
復原事務:rollback
設定自動送出:set autocommit 1 | 0
atuoCommit系統預設是1立即送出模式;如果要手動控制事務,需要設定set autoCommit 0;
這樣我們就可以用commit、rollback來控制事務了。
在一段語句塊中禁用autocommit 而不是set autocommit
start transaction;
select @result := avg(age) from temp;
update temp set age = @result where id = 2;
select * from temp where id = 2;//值被改變
rollback;//復原
select * from temp where id = 2;//變回來了
在此期間隻有遇到commit、rollback,start Transaction的禁用autocommit才會結束。然後就恢複到原來的autocommit模式;
不能復原的語句
有些語句不能被復原。通常,這些語句包括資料定義語言(DDL)語句,比如建立或取消資料庫的語句,
和建立、取消或更改表或存儲的子程式的語句。
您在設計事務時,不應包含這類語句。如果您在事務的前部中釋出了一個不能被復原的語句,
則後部的其它語句會發生錯誤,在這些情況下,通過釋出ROLLBACK語句不能 復原事務的全部效果。
一些操作也會隐式的送出事務
如alter、create、drop、rename table、lock table、set autocommit、starttransaction、truncate table 等等,
在事務中出現這些語句也會送出事務的
事務不能嵌套事務
事務的儲存點
Savepoint pointName/Rollback to savepoint pointName
一個事務可以設定多個儲存點,rollback可以復原到指定的儲存點,恢複儲存點後面的操作。
如果有後面的儲存點和前面的同名,則删除前面的儲存點。
Release savepoint會删除一個儲存點,如果在一段事務中執行commit或rollback,則事務結束,是以儲存點删除。
Set Transaction設計資料庫隔離級别
SET [GLOBAL | SESSION] TRANSACTION ISOLATION LEVEL
{ READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE }
本語句用于設定事務隔離等級,用于下一個事務,或者用于目前會話。
在預設情況下,SET TRANSACTION會為下一個事務(還未開始)設定隔離等級。
如果您使用GLOBAL關鍵詞,則語句會設定全局性的預設事務等級,
用于從該點以後建立的所有新連接配接。原有的連接配接不受影響。使用SESSION關鍵測可以設定預設事務等級,
用于對目前連接配接執行的所有将來事務。
預設的等級是REPEATABLE READ全局隔離等級。
Ø 注釋
select 1+1; # 單行注釋
select 1+1; -- 單行注釋
select 1 /* 多行注釋 */ + 1;
Ø 基本資料類型操作
字元串
select \'hello\', \'"hello"\', \'""hello""\', \'hel\'\'lo\', \'/\'hello\';
select "hello", "\'hello\'", "\'\'hello\'\'", "hel""lo", "/"hello";
/n換行
select \'This/nIs/nFour/nLines\';
/轉義
select \'hello / world!\';
select \'hello /world!\';
select \'hello // world!\';
select \'hello /\' world!\';
Ø 設定資料庫mode模式
SET sql_mode=\'ANSI_QUOTES\';
create table t(a int);
create table "tt"(a int);
create table "t""t"(a int);
craate talbe tab("a""b" int);
Ø 使用者變量
set @num1 = 0, @num2 = 2, @result = 0;
select @result := (@num1 := 5) + @num2 := 3, @num1, @num2, @result;
Ø 存儲過程
建立存儲過程:
delimiter //
create procedure get(out result int)
begin
select max(age) into result from temp;
end//
調用存儲過程:
call get(@temp);
查詢結果:
select @temp;
删除存儲過程:
drop procedure get;
檢視存儲過程建立語句:
show create procedure get;
select…into 可以完成單行記錄的指派:
create procedure getRecord(sid int)
begin
declare v_name varchar(20) default \'jason\';
declare v_age int;
declare v_sex bit;
select name, age, sex into v_name, v_age, v_sex from temp where id = sid;
select v_name, v_age, v_sex;
end;
call getRecord(1);
Ø 函數
函數類似于存儲過程,隻是調用方式不同
例如:select max(age) from temp;
建立函數:
create function addAge(age int) returns int
return age + 5;
使用函數:
select addAge(age) from temp;
删除函數:
drop function if exists addAge;
drop function addAge;
顯示建立文法:
show create function addAge;
Ø 遊标
聲明遊标:declare cur_Name cursor for select name from temp;
打開遊标:open cur_Name;
Fetch遊标:fetch cur_Name into @temp;
關閉遊标:close cur_Name;
示例:
CREATE PROCEDURE cur_show()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE v_id, v_age INT;
DECLARE v_name varchar(20);
DECLARE cur_temp CURSOR FOR SELECT id, name, age FROM temp;
DECLARE CONTINUE HANDLER FOR SQLSTATE \'02000\' SET done = 1;
OPEN cur_temp;
REPEAT
FETCH cur_temp INTO v_id, v_name, v_age;
IF NOT done THEN
IF isnull(v_name) THEN
update temp set name = concat(\'test-json\', v_id) where id = v_id;
ELSEIF isnull(v_age) THEN
update temp set age = 22 where id = v_id;
END IF;
END IF;
UNTIL done END REPEAT;
CLOSE cur_temp;
END
Ø 觸發器
觸發器分為insert、update、delete三種觸發器事件類型
還有after、before觸發時間
建立觸發器:
create trigger trg_temp_ins
before insert
on temp for each row
begin
insert into temp_log values(NEW.id, NEW.name);
end//
删除觸發器:
drop trigger trg_temp_ins