一、數據庫簡單介紹
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