1. 概述
MySQL是一個(gè)關(guān)系型數(shù)據(jù)庫管理系統(tǒng)柬批,由瑞典MySQL AB 公司開發(fā)若河,屬于 Oracle 旗下產(chǎn)品镊讼。MySQL 是最流行的關(guān)系型數(shù)據(jù)庫管理系統(tǒng)之一,在 WEB 應(yīng)用方面耳峦,MySQL是最好的 RDBMS (Relational Database Management System,關(guān)系數(shù)據(jù)庫管理系統(tǒng)) 應(yīng)用軟件之一碳褒。
摘自:百度百科
2. 安裝(Mac版)
-
雙擊開始安裝
- 備注:安裝過程會生成隨機(jī)的root密碼应役,需要保存起來
安裝結(jié)束后,到系統(tǒng)偏好設(shè)置里啟動(dòng)MySQL服務(wù)
-
配置環(huán)境變量
- vim ~/.bash_profile
- 配置變量
export PATH=$PATH:/usr/local/mysql/bin
- source ~/.bash_profile 生效命令
-
登錄mysql唆阿,輸入之前安裝時(shí)生成的密碼
mysql -u root -p
-
修改密碼
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('123456');
-
重置密碼
- 先關(guān)閉MySQL服務(wù)
- 切換當(dāng)前目錄到mysql安裝目錄 bin下
- 調(diào)用 sudo ./mysqld_safe --skip-grant-tables 將自動(dòng)重啟mysql益涧,這時(shí)可以免密登錄
- 打開另外一個(gè)終端,直接用執(zhí)行mysql驯鳖,登錄mysql
- 輸入:mysql> FLUSH PRIVILEGES; 清除無密登錄設(shè)置
- SET PASSWORD FOR 'root'@'localhost' = PASSWORD('123456'); 設(shè)置密碼闲询,即可
配置支持中文
到/etc 路徑下新建配置文件
vim my.cnf
輸入
[mysqldump]
quick
max_allowed_packet = 16M
[mysql]
no-auto-rehash
# Remove the next comment character if you are not familiar with SQL
#safe-updates
[client]
default-character-set=utf8
[mysqld]
character-set-server=utf8
[myisamchk]
key_buffer_size = 20M
sort_buffer_size = 20M
read_buffer = 2M
write_buffer = 2M
[mysqlhotcopy]
interactive-timeout
保存后,重新啟動(dòng)服務(wù)即可
- 其他系統(tǒng)安裝可以參考:Linux和Windows MYSQL安裝教程
3. 常用基礎(chǔ)命令
- 登錄命令
mysql -u<name> -p<password>
或
mysql -u <name> -p (后續(xù)提示輸入密碼)
- 退出mysql命令模式
exit;
- 查尋數(shù)據(jù)庫中所有的數(shù)據(jù)庫
show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
- 選中其中一個(gè)數(shù)據(jù)庫進(jìn)行操作
use <db name>;
- 顯示數(shù)據(jù)庫下所有的表
show tables;
- 查看表結(jié)構(gòu)
describe <tableName>
- 創(chuàng)建數(shù)據(jù)庫
create database <db name>
- 創(chuàng)建表
CREATE TABLE <table name> (<property name> <type>, <property name> <type>, ...);
- 插入數(shù)據(jù)(增)
INSERT INTO <table name> VALUES (<property>, <property>, ...);
- 刪除數(shù)據(jù)
DELETE FROM <table name> <condition>;
- 修改數(shù)據(jù)
UPDATE <table name> SET <property>=<value> <condition>;
- 查詢數(shù)據(jù)
SELECT <propertys> FROM <table name> <condition>;
-
去重查尋
select distinct <propertys> from <table name>;
-
查尋某字段滿足或條件
select <propertys> from <table name> where <property> in (value1,value2,...);
或
select <propertys> from <table name> where <property>=value1 or <property>=value2 or ...; -
查尋某字段處于某區(qū)間內(nèi)
select <propertys> from <table name> where <property> between value1 and value2;
或
select <propertys> from <table name> where <propery> > value1 and <propery> < value2; -
升序查尋
select * from <table name> order by <property> asc;
-
降序查尋
select * from <table name> order by <propery> desc;
-
聯(lián)合字段升降序查尋
select * from <table name> order by <property1> desc, <property2> asc;
-
查尋條數(shù)
select count(<property>) from <table name> <condition>;
-
查尋字段最大值
select max(<property>) from <table name>;
-
查尋字段最小值
select min(<property>) form <table name>;
-
查尋某字段最大值整條記錄
select * from <table name> order by <property> desc limit 0,1;
注:limit第一個(gè)表示起始位置浅辙,第二個(gè)表示個(gè)數(shù)
或
select * from <table name> where <property>=(select max<property> from <table name>); -
查尋某字段最小值整條記錄
select * from <table name> order by <property> asc limit 0,1;
-
記算字段平均值
select avg(property) from <table name>;
-
分組查詢
select <property> from <table name> group by <property>;
除了group by 的屬性嘹裂,必需保證查詢的字段是數(shù)值是唯一的
group by 篩選--having
select <property> from <table name> group by <property> having <condition>; -
模糊查詢
以x開頭
select * from <table name> like 'x%';
以x結(jié)尾
select * from <table name> like '%x';
中間包含x
select * from <table name> like '%x%';
% 表示多個(gè)任意字母
_ 表示一個(gè)任意字母 -
多表查詢
select <table name1>.<property1>,<table name2>.<property2> from <table name1>,<table name2> <conditions>
如果表之間的字段名不會相同的話,select 后面的字段名前的table name 可以省略摔握。<conditions>這個(gè)條件需要包含各表之前的聯(lián)系。 -
查詢年 year
select year(<property>) from <table name>
-
使用正則表達(dá)式
select * from <table name> where <property> regexp <condition>;
-
字段拼接
select concat(<property1>,<property2>,...) from <table name>;
-
去空格函數(shù)
select concat(RTrim(<property1>),RTrim(<property2>) from <table name>;
RTrim 去除右邊空格
LTrim 去除左邊空格 -
union合并兩個(gè)查詢結(jié)果
select <property> from <table name> <condition>
union
select <property> from <table name> <condition>; -
any 和比較操作符一起使用丁寄,表示對比項(xiàng)只要any中的任意一項(xiàng)滿足氨淌,則為true。
select * from <table name> where <property> > any(select <property> from <table name> where <condition>);
-
all 和經(jīng)較符一起使用伊磺,表示對比項(xiàng)需要滿足all中的所有項(xiàng)盛正,才為true
select * from <table name> where <property> > all(select <property> from <table name> where <condition>);
-
復(fù)制表做條件查詢
select * from <table name> a where <property> < (select avg(<property> from <table name> b where a.<property1>=b.<property1>)
-
取反模糊查詢
select * from <table name> where not like <condition>;
- 修改表
alter table <table name> <operation>;
- 查看表創(chuàng)建語句
show create table <table name>;
- 使表支持中文
alter table <table name> convert to character set utf8;
- 清空表數(shù)據(jù)
truncate table <table name>;
- 刪除數(shù)據(jù)庫
drop database <database name>
4. 數(shù)據(jù)類型
-
數(shù)值類型
-
日期類型
-
字符串類型
char、varchar屑埋、text這三種類型比較:
(1)char: char 不用多說了豪筝,它是定長格式的,但是長度范圍是 0~255. 當(dāng)你想要儲存一個(gè)長度不足 255 的字符時(shí)摘能,Mysql 會用空格來填充剩下的字符续崖。因此在讀取數(shù)據(jù)時(shí),char 類型的數(shù)據(jù)要進(jìn)行處理团搞,把后面的空格去除严望。
(2)varchar: 關(guān)于 varchar,有的說最大長度是 255逻恐,也有的說是 65535像吻,查閱很多資料后發(fā)現(xiàn)是這樣的:varchar 類型在 5.0.3 以下的版本中的最大長度限制為 255峻黍,而在 5.0.3 及以上的版本中,varchar 數(shù)據(jù)類型的長度支持到了 65535拨匆,也就是說可以存放 65532 個(gè)字節(jié)(注意是字節(jié)而不是字符D飞!2衙俊)的數(shù)據(jù)(起始位和結(jié)束位占去了3個(gè)字節(jié))骨饿,也就是說,在 5.0.3 以下版本中需要使用固定的 TEXT 或 BLOB 格式存放的數(shù)據(jù)可以在高版本中使用可變長的 varchar 來存放洪鸭,這樣就能有效的減少數(shù)據(jù)庫文件的大小样刷。
(3)text: 與 char 和 varchar 不同的是,text 不可以有默認(rèn)值览爵,其最大長度是 2 的 16 次方-1
總結(jié)起來置鼻,有幾點(diǎn):
經(jīng)常變化的字段用 varchar
知道固定長度的用 char
盡量用 varchar
超過 255 字符的只能用 varchar 或者 text
能用 varchar 的地方不用 text
5. MySQL約束條件
1. 主鍵約束
定義:為屬性添加一個(gè)約束可以唯一確定表中的一條記錄,該屬性不能重復(fù)也不能為空蜓竹。
CREATE TABLE t_user (
id INT primary key,
name VARCHAR(20)
);
- 聯(lián)合主鍵
定義:由多個(gè)屬性組成主鍵箕母,每個(gè)屬性都不能為空,且每個(gè)屬性不完全相同
CREATE TABLE t_user (
id INT,
name VARCHAR(20),
sex CHAR(1),
PRIMARY KEY(id, name)
);
//都可以成功插入數(shù)據(jù)
INSERT INTO t_user VALUES(1,'Jack','F');
INSERT INTO t_user VALUES(1,'Rose, 'M');
INSERT INTO t_user VALUES(2,'Jack;,'F');
// 無法插入數(shù)據(jù)
INSERT INTO t_user VALUES(null,'Machel','F');
- 修改主鍵約束
新增主鍵約束
alter table t_student add primary key(name);
// 或
alter table t_sutdent name varchar(20) primary key;
刪除主鍵
alter table t_student drop primary key;
2. 自增約束
定義:屬性設(shè)置自增約束后俱济,插入數(shù)據(jù)時(shí)不需要帶對應(yīng)屬性嘶是,其值會在最后一條記錄的基礎(chǔ)上加1。一般和主鍵約束一起全使用蛛碌。
create table t_user2 (
id int primary key auto_increment,
name varchar(20)
);
insert into t_user2(name) values('James');
//可以指定id但是不能重復(fù)
insert into t_user2 values(4,'Jack');
3聂喇、唯一約束
定義:字段添加唯一約束后,表中該字段的所有值不能重復(fù)蔚携。和主鍵的區(qū)別為希太,唯一約束值可以為空。比如實(shí)際場景中用戶的身份證酝蜒。
create table t_user3 (
id int primary key auto_increment,
name varchar(20) unique
);
// 或者
create table t_user3 (
id int primary key auto_increment,
name varchar(20),
unique(name)
);
使用alter進(jìn)行修改
/* add*/
alter table t_user3 add unique(name);
alter table t_user3 modify name varchar(20) unique;
/* delete*/
alter table t_user3 drop index name;
- 聯(lián)合唯一
定義:由多個(gè)屬性組成唯一性誊辉,屬性可以為空,且每個(gè)屬性不完全相同(都為空例外)
create table t_user3 (
id int primary key auto_increment,
name varchar(20),
psw varchar(20),
unique(name亡脑,psw)
);
4. 非空約束
定義:定義字段不能為空堕澄。
create table t_user4 (
id int primary key auto_increment,
account varchar(30) not null,
password varchar(30 not null
);
5. 默認(rèn)約束
定義:插入一條記錄,如果字段沒有寫入值霉咨,則會自動(dòng)填充設(shè)好的默認(rèn)值蛙紫。
create table t_user5 {
id int primary key auto_increment,
name varchar(30),
password varchar(30) default '123456'
}
6. 外鍵約束
定義:一個(gè)字段的值為另一張表的主鍵,該約束值可以重重躯护,也可以為空惊来。
作用:保持?jǐn)?shù)據(jù)的一致性。1棺滞、從表外鍵字段不能插入主表主鍵字段沒有的值 2裁蚁、主表不能直接刪除被從表引用的記錄
/*主表*/
create table t_class (
id int primary key auto_increment,
name varchar(30) unique not null
);
/*從表*/
create table t_student (
id int primary key auto_increment,
name varchar(30) not null,
classid int,
foreign key(classid) references t_class(id)
);
6.設(shè)計(jì)范式
1. 第一范式
設(shè)計(jì)表時(shí)矢渊,每個(gè)字段都具有原子特性,不可分割枉证。比如:地址字段設(shè)計(jì)成一個(gè)字段矮男,那就不滿足該條件,因?yàn)檫@個(gè)字段可以分為:國家室谚、省毡鉴、城市、區(qū)秒赤、門牌號等猪瞬。
這一原則并不是一定要遵守:
1、好處是當(dāng)你要去查數(shù)據(jù)時(shí)入篮,可以對數(shù)據(jù)進(jìn)行更加祥細(xì)的分類陈瘦。
2、壞外是如果你需要查的數(shù)據(jù)為各個(gè)字段的組合潮售,你需要每次進(jìn)拼接等額外操作痊项。
這里總結(jié)為 字段原子范式。
2. 第二范式
滿足第一范式的前提下酥诽,設(shè)計(jì)表時(shí)鞍泉,表中的每個(gè)字段都必須依賴于主鍵,不能只依賴于主鍵的一部分(聯(lián)合主鍵的情況)肮帐。
Eg:
有一張訂單表如下:t_order 主鍵為聯(lián)合主鍵(id, product_id)
id | product_id | customer_id | product_name | customer_name |
---|
因?yàn)閜roduct_name 是完全不依賴于主鍵的咖驮,只與product_id相關(guān),這就不滿足第二范式训枢。為此我們應(yīng)該把進(jìn)行拆表來滿足這個(gè)設(shè)計(jì)范式游沿。
訂單表:t_order:
id | product_id | customer_id |
---|
商品表:t_product
product_id | product_name |
---|
顧客表:t_customer
customer_id | customer_name |
---|
這樣就滿足了第二設(shè)計(jì)范式了。
這里總結(jié)為:主鍵完全依賴范式
3. 第三范式
滿足第二范式的前提下肮砾,要求表中的每個(gè)字段都必須直接依賴于主鍵,而不是間接依賴袋坑。
Eg:
表t_order 中product_name 和主鍵并沒有直接的依賴仗处,而是依賴于表中product_id的值,就不滿足第三范式
id | product_id | product_name | customer |
---|
我們需要修改下:
id | product_id | customer |
---|
商品表:t_product
product_id | product_name |
---|
這樣子就使表中的每個(gè)字段都是直接依賴于主鍵了枣宫。
這里總結(jié)為:主鍵非間接依賴范式
7. 事務(wù)
定義
事務(wù)是mysql執(zhí)行任務(wù)的最小單位婆誓。
事務(wù)提交
事務(wù)提交后將對之前執(zhí)行的sql語句進(jìn)行持久化,數(shù)據(jù)將無法回滾也颤,當(dāng)前事務(wù)結(jié)束
- 自動(dòng)提交
自動(dòng)提交開啟后洋幻,每次執(zhí)行一條sql語句后,都將馬上提交并且返回結(jié)果翅娶。
查看自動(dòng)提交狀態(tài)select @@autocommit;
默認(rèn)是開啟的文留。
設(shè)置自動(dòng)提交配置
0 為關(guān)閉 1 為開啟
set autocommit=0;
- 手動(dòng)提交
手動(dòng)提交為在執(zhí)行完一些sql語句后好唯,手動(dòng)調(diào)用命令進(jìn)行提交
命令:commit;
事務(wù)回滾
事務(wù)回滾,可以把未提交的sql語名執(zhí)行結(jié)果進(jìn)行撤銷燥翅。
命令:
rollback;
手動(dòng)開啟事務(wù)
在自動(dòng)提交的狀態(tài)下骑篙,也可以開啟手動(dòng)提交事務(wù)。
命令:
begin;
或
start transaction;
事務(wù)的四大特征(ACID)
A: 原子性:事務(wù)是執(zhí)行sql任務(wù)的最小單位森书,不可分割
C: 一致性:事務(wù)里面的sql語句執(zhí)行結(jié)果是一致的靶端,要么都成功,要么都失敗
I: 隔離性:兩個(gè)事務(wù)之間都是各自獨(dú)立的
D: 持久性:事務(wù)一旦提交后凛膏,數(shù)據(jù)交被持久化杨名,回去回滾
隔離級別
-
mysql的隔離級別分為四種:
- read uncommitted;(可讀取未提交內(nèi)容)
事務(wù)A可以查詢到事務(wù)B還未提交的事務(wù)的修改結(jié)果,如果事務(wù)B進(jìn)行rollback操作后猖毫,會使事務(wù)A之前查詢到的結(jié)果為錯(cuò)誤的台谍,這種現(xiàn)象稱為 臟讀。 - read committed;(可讀取已提交內(nèi)容)
可以解決臟讀問題鄙麦,事務(wù)A只可以查詢到事務(wù)B已經(jīng)提交后的數(shù)據(jù)典唇,這就會造成事務(wù)A在事務(wù)B提交前和提交后查詢的結(jié)果不一致,這種情況稱為 不可重復(fù)讀 - repeatable read;(可重讀)
可以解決臟讀胯府、不可重復(fù)讀的問題介衔,但是會出現(xiàn)幻讀。分別開啟事務(wù)A和事務(wù)B骂因,對當(dāng)前數(shù)據(jù)進(jìn)行查詢炎咖,此時(shí)對事務(wù)B進(jìn)行數(shù)據(jù)修改,然后提交寒波。再次在事務(wù)A中對數(shù)據(jù)進(jìn)行查詢會發(fā)現(xiàn)的數(shù)據(jù)還是不變的乘盼,這種情況稱為 幻讀 - serializable;(可串行化)
完全鎖住數(shù)據(jù),當(dāng)有事務(wù)A進(jìn)行對數(shù)據(jù)進(jìn)行修改時(shí)俄烁,其它事務(wù)要進(jìn)行讀寫操作時(shí)绸栅,會進(jìn)行等待,直到事務(wù)A提交結(jié)束页屠。
越高的隔離級別問題越少粹胯,但是性能也相對應(yīng)的會變得更差。
以下為各個(gè)隔離級別問題表
- read uncommitted;(可讀取未提交內(nèi)容)
隔離級別 | 臟讀 | 不可重復(fù)讀 | 幻讀 |
---|---|---|---|
read uncommitted | 1 | 1 | 1 |
read committed | 0 | 1 | 1 |
repeatable read | 0 | 0 | 1 |
serializable | 0 | 0 | 0 |
-
隔離級別的查詢和設(shè)置
查詢select @@tx_isolation;(8.0前)
select @@transation_isolation;(8.0后)
+------------------+
| @@tx_isolation |
+------------------+
| READ-UNCOMMITTED |
+------------------+設(shè)置
set session transaction isolation level read uncommitted;
8. 表的鏈接
1. 交叉連接 cross join
定義:交叉連接也叫叫笛卡爾積連接辰企,第一張表是 a 的每條記錄會和第二張表b 中的每條記錄進(jìn)行組合风纠。
- 隱式交叉連接
select * from A, B;
- 顯式交叉連接
select * from A cross join B;
2. 內(nèi)連接 inner join
定義:內(nèi)連接又叫等值連接,通過比較運(yùn)算符根據(jù)表共有的列匹配出行
- 隱式內(nèi)連接
select * from A, B where A.id=B.id;
- 顯式內(nèi)連接
select * from A inner join B on A.id=B.id;
3. 外連接 outer join
定義:外聯(lián)接可以是左向外聯(lián)接牢贸、右向外聯(lián)接或完整外部聯(lián)接竹观。也就是說外連接又分為:左外連接、右外連接、全外連接臭增。外連接需要有主表或者保留表的概念
通過業(yè)務(wù)需求懂酱,分析主從表
如果使用 LEFT JOIN ,則主表在它左邊
如果使用 RIGHT JOIN 速址,則主表在它右邊
查詢結(jié)果以主表為主玩焰,從表記錄匹配不到,則補(bǔ) null
- 左外連接 left outer join 或 left join
select * from A left outer join B on A.id=B.id;
- 右外連接 right outer join 或 right join
select * from A right outer join B on
A.id=B.id; - 全外連接 mysql 不支持芍锚,可以通過union的方式實(shí)現(xiàn)
select * from A left outer join B on A.id=B.id
union
select * from A right outer join B on
A.id=B.id;