硬核!萬字Mysql知識總結

一 mysql登錄

遠程登錄方式
本地登陸方式
mysql:mysql -h 主機名 -P 端口號 -u 用戶名 -p密碼
mysql:mysql -uroot -p密碼
二 數據庫操作命令

創建數據庫、刪除數據庫、展示所有數據庫名。
查看當前數據庫名、查看所有表、查看其他數據庫的表。
查看數據庫的版本、表結構、以及字符集、數據庫引擎
– 如果該數據庫不存在,創建該數據庫
create database if not exists 數據庫名;

– 設置指定數據庫的字符集爲gbk/uft8
alter database 數據庫名 character set gbk/uft8;

– 如果該數據庫存在刪除該數據庫
drop database if exists 數據庫名 ;

– 查看所有數據庫
show databases;

– 使用數據庫
use 數據庫名;

– 在當前數據庫下查看所有表格
show tables;

– 查看其他數據庫的全部表格
show tables from 數據庫名;

– 查看當前數據庫名
select database();

– 查看當前MySQl登陸的用戶
select user();

– 查看當前數據庫的版本
select version();

– 查看錶結構
desc 表名;

– 查看數據庫的字符集
show variables like ‘%character%’;
show variables like ‘%char%’;
show variables like ‘collation%’;

– 查看數據庫的引擎
show engines;

三 表操作命令

創建表、修改表數據(插入表數據、修改表數據、刪除表數據、查詢表數據)。
修改表結構(新增字段、修改表字段、增加主鍵、調整字段順序、指定位置添加字段)。
根據原表創建新表(僅複製表結構、複製表結構和數據、複製部分表字段和表數據)。
– 創建員工表,先在數據庫裏面創建該表,爲了後面做測試用
create table dept(
department_id int primary key auto_increment, – 部門編號
dname varchar(14) , – 部門名字
location varchar(13) – 地址
);

create table employee(
employee_id int primary key auto_increment, – 員工編號
c_name varchar(20), – 員工中文名
e_name varchar(20), – 員工英文名
hiredate date, – 僱傭日期,入職日期
salary int, – 薪水
comm int, – 獎金
job_id int, – 所屬工種
department_id int not null, – 部門編號
manager_id int – 直接領導編號
);

– 表中插入數據
insert into dept values(10,‘財務部’,‘北京’);
insert into dept values(20,‘研發部’,‘上海’);
insert into dept values(30,‘銷售部’,‘廣州’);
insert into dept values(40,‘行政部’,‘深圳’);
insert into dept values(50,‘人力資源’,‘惠州’);
– 表中插入數據
insert into employee values(1,‘劉一’,‘liuyi’,‘1980-12-17’,7902,800,1,10,2);
insert into employee values(2,‘陳二’,‘chener’,‘1981-02-20’,7698,1600,3,30,3);
insert into employee values(3,‘張三’,‘zhangsan’,‘1981-02-22’,7698,1250,5,30,4);
insert into employee values(4,‘李四’,‘lisi’,‘1981-04-02’,7839,2975,2,20,5);
insert into employee values(5,‘王五’,‘wangwu’,‘1981-09-28’,7698,1250,1,40,0);
insert into employee values(6,‘趙六’,‘zhaoliu’,‘1981-05-01’,7839,2850,3,50,5);

– 更新數據:
update employee set c_name =“劉一一” where id=1;

– 刪除數據:
delete from employee where id=1;

– 查詢數據
select * from employee where id in(1,4);

– 修改表名
alter table 舊錶名 rename to 新表名;

– 修改表註釋
alter table 表名 comment ‘系統信息表’;

– 修改字段類型和註釋
alter table 表名 modify column 字段名 varchar(20) COMMENT ‘新的註釋’;

– 設置字段允許爲空
alter table 表名 modify column 字段名 varchar(255) null COMMENT ‘新註釋’;

– 增加一個字段,設好數據類型,且不爲空,添加註釋
alert table 表名 add 字段名 varchar(255) not null comment ‘新註釋’;

– 增加非空、自增主鍵
alter table 表名 add 字段名 int(5) not null auto_increment ,add primary key (aid);

– 修改字段名字(要重新指定該字段的類型)
alter table t_app change 原字段名 新字段名 varchar(20) not null;

– 刪除字段
alter table 表名 drop 字段名;

– 在某個字段後增加字段
alter table 表名 add column 新字段名 int not null default 0 after 字段名;

– 調整字段順序
alter table employee change num num int not null after departmen_id ;

– 表的刪除
drop table 表名 ;

–複製表的結構,不復製表數據
create table 新表名 like 舊錶名;

–複製表的結構,同時也複製表數據
create table 新表名 select * from 舊錶名;

–只複製部分表結構和對應的數據,並且帶篩選條件
create table user1 select id, name,salary from user where salary>3000;

–僅複製部分字段
create table user2 select id, name from user;

3.2 表約束
NOT NULL: 非空約束
DEFAULT: 默認,用於保證該字段有默認值。
PRIMARY KEY:主鍵約束
UNIQUE: 唯一約束
CHECK: 檢查約束
FOREIGN KEY:外鍵約束。
create table student (
id int,
name varchar(20) ,
gender char(1) ,
seat int,
age int,
class_id int,

PRIMARY KEY(id), – 主鍵
UNIQUE (seat), – 唯一鍵
CHECK(gender=“男” or gender=“女”),-- 檢查
FOREIGN KEY (class_id) REFERENCES class (id) – 外鍵
)
註釋:這些約束在你創建表和修改表的時候都可以使用。

表查詢

distinct(去重)
limit(分頁查詢)
offset(跳過多少條)
UNION 和 UNION ALL(聯合查詢)
like(模糊查詢)
where、between、in、or、and條件關鍵字
order by (asc升序、desc降序排序)
group by (分組查詢)
having 關鍵字
case(流程控制)
– distinct(去重)
select distinct 字段名 from 表名;

– limit(初始記錄行的偏移量是 0(而不是 1),第一個參數指定第一個返回記錄行的偏移量,第二個參數指定返回記錄行的最大數目。)
select * from 表名 limit 5,10; – 檢索記錄行6-15

– offset(跳過多少條)
selete * from employee limit 2 offset 1;
±—±---------±------±-------------±-----+
| 2 | lisi | 12000 | 40 | 90 |
| 3 | wangwu | 0 | 50 | 0 |
±—±---------±------±-------------±-----+
– 注意:
– 1.數據庫數據計算是從0開始的
– 2.offset X是跳過X個數據,limit Y是選取Y個數據
– 3.limit X,Y 中X表示跳過X個數據,讀取Y個數據

–union 和union all(union all是直接連接,取到得是所有值,記錄可能有重複 union 是取唯一值,記錄沒有重複。)

– UNION 的語法如下:
[SQL 語句 1]
UNION
[SQL 語句 2]

– UNION ALL 的語法如下:
[SQL 語句 1]
UNION ALL
[SQL 語句 2]

– UNION全連接查詢,把部門表和員工表的所有數據都查出來,若有兩個表都有匹配數據的就顯示匹配數據,若其中有一個表在另一個表中沒有匹配數據的輸就顯示爲null
select e.ename,d.dname
FROM employee e
left JOIN dept d
ON e.department_id= d.department_id
UNION
select e.ename,d.dname
FROM employee e
right JOIN dept d
ON e.department_id= d.department_id;
±-------±---------+
| ename | dname |
±-------±---------+
| 劉一 | 財務部 |
| 陳二 | 銷售部 |
| 張三 | NULL |
| 李四 | 研發部 |
| 王五 | 行政部 |
| 趙六 | 人力資源 |
±-------±---------+

– 模糊查詢:like,%標識匹配任意哥字符,_表示匹配一個字符
– 查詢employee表裏面名字含有豪字的員工的全部信息
select * form employee where c_name like ‘%豪%’;

– 查詢員工名中第三個字母爲a,第五個字母爲b的員工信息;
select * from employee where c_name like ‘__達_法%’;

– 當查詢的信息信息看裏面還有_這樣的特殊字符;
select * from employee where c_name like ‘__%’;

– 查詢工資在5000到6000之間的員工信息;
select * from employee where salary between 5000 and 6000;

– in、or、and關鍵字
select * from dept where location in (‘北京’,‘上海’);
select * from dept where location =‘北京’ or location =‘上海’ ;
select * from employee where (department_id=30 or department_id=40) and salary >3000;

– 選擇工資不在3000到5000的員工的姓名和工資,按工資降序
select name, salary, department_id from employees where salary not between 3000 and 5000 order by salary desc;

– 查詢每個部門的員工個數
select count (*) , department_ id from employee group by department_ id;

– 給30號部門的增加500,40號部門增加1000,50號部門增加1500
select *, (
case department_id
when 30 then
salary+500
when 40 then
salary+1000
when 50 then
salary+1500
else salary
end
) ‘漲後工資’
from
employee;

– 顯示員工的薪資等級
select *, (
case
when salary >=7900 then
‘高薪資’
when salary >=7800 then
‘中等薪資’
when salary >=7700 then
‘低薪資’
else
‘太難了’
end
) ‘薪資等級’
from
employee
order by salary desc;

– 語法格式
select 字段1,字段2,字段3 from 表名 [where 篩選條件] [group by 分組] [having 篩選條件1] [order by 排序列表]
mysql字符串函數

concat():拼接字符串
substr():截取字符串
instr():獲取子串第一次出現的索引
lpad():左邊以指定字符填充到指定長度
rpad():右邊以指定字符填充到指定長度
upper():轉換爲大寫
lover():轉換爲小寫
replace():替換函數
length():獲取字節長度
trim():去掉字符串前後空格
– 將英文名全部轉換大寫和全部轉換爲小寫,然後進行拼接。
select concat(upper(e_name) ,lower(e_name)) from employee;

– substr,注意:索引從1開始,截取從指定索引處後面所有字符
select substr("歡迎關注非科班的科班,帶你一起提升代碼內功’,7) str ;

– 從指定索引截取指定長度的字符串substr(str,num1,num2)第二個參數時索引、第三個參數是指定的長度。
select substr(‘歡迎關注非科班的科班,帶你一起提升代碼內功’,5,6) str;

– 姓名中首字符大寫,其他字符小寫然後用_拼接,顯示出來
SELECT CONCAT (UPPER (SUBSTR(last_ name,1,1)),’’ ,LOWER (SUBSTR(last name,2))) out_put
FROM employees;

– instr返回子串在指定字符串第一次出現的素引,如果找不到返回0
select instr(‘歡迎關注,帶你一起提升代碼內功’, haha’) as str;

– length獲取字符串長度、trim()去掉字符串前後的空字符串
select length(trim(" haha ")) as str;

– lpad用指定的字符實現左填充指定長度
select lpad(‘haha’,9,’*’) as str;

– rpad用指定的字符實現右填充指定長度
select rpad(‘haha’,9,’*’) as str;

– replace 替換
select replace(‘haha’, ‘科班’,‘javaboy’) as str;
mysql字符串函數

now:返回當前的日期和時間
year:返回年份
month:返回月份
monthname:以英文形式返回月份
day:返回日
hour:小時
mimute:分鐘
second:秒
datediff:返回兩個日期相差的天數
date_format:將時間日期轉換爲字符串
str_to_date:將字符轉換成日期
curdate:返回當前日期,不包含時間
curtime:返回當前時間,不包含日期
– now()返回當前系統日期+時間
select now();

– curdate返回當前系統日期,不包含時間,curtime返回當前時間,不包含日期
select curdate();
select curtime();

– 可以獲取指定的部分,年、月、日、小時、分鐘、秒
select year(now())年;
select year(‘2020-1-1’) 年;
select year(hiredate) 年 from employee;
select month(now()) 月;
select monthname(now()) 月;

– %Y 四位的年份
– %y 2位的年份
– %m 2位的月份( 01,02…11,12)
– %c 1位的月份( 1,2…11,12)
– %d 日( 01,02,… )
– %H 24小時制的小時
– %h 12小時制的小時
– %i 分鐘( 00,01…59)
– %s 秒( 00,01…59)

– str_to_date:將字符串轉換爲指定格式的日期對象
select str_to_date(‘4-22-2020’,’%m-%d-%Y’);

– 查詢入職日期爲2020-4-22的員工信息
select * from employee where hiredate = ‘2020-4-22’ ;

– date_format:將日期轉換成字符
select date_format(‘2020/02/28’,’%Y年%m月 %d日’);
select date_format(now(), ‘%y年%m月%d日’) as date ;

– 查詢工資大於7800的員工的中文名、入職日期
select c_name 中文名, date_format(hiredate,’%m月/%d日 %y年’) 入職日期 from employee where salary>7800;
mysql數學函數

ceil:中文意思表示天花板,表示向上取整
floor:中文意思表示地板,表示向下取整
round:對數字取四捨五入
rand:隨機取0-1之間的所及小數
mod:取模運算
truncate:截取,類似於字符串的substr的用法
– ceil表示向上取整。整數:返回本身。小數:返回的是與該數相鄰並比該數大的整數
select ceil(2) ;
select ceil(2.21) ;
select ceil(-2) ;
select ceil(-2.1) ;

– floor向下取整。整數:返回本身。小數:返回的是與該數相鄰並比該數大的整數
select floor(2) ;
select floor(2.21) ;
select floor(-2) ;
select floor(-2.1) ;

– rand在0-1之間隨機去一個隨機數
select round(rand()*10) ; --取一個0-10的隨機整數

– round對數字取四捨五入
select round(-1.55) ;
select round(1.567,2) ;

– mod取餘運算
select mod(3,2) ;
select 3%2;

– truncate截取,第一個是要截取的數字,第二個是要截取的位數,從小數點後開始算
select truncate(2.3345534,1) ;
創建視圖和索引

視圖view,創建,查詢視圖,刪除視圖
索引index,創建索引,刪除索引
語法格式如下:
create view <視圖名> [新字段名1,新字段名2,新字段名3,新字段名4,…] as <select語句>

–創建一個員工的視圖
create view v_employee (id,name,sal,department,hiredate)
as select employee_id,c_name,salary,department_id,hiredate
from employee ;

–查詢視圖
select * from v_employee where sal>7800;

–修改視圖
alter view v_employee as select * from employee where salary>7800;

–刪除視圖
drop view v_employee ;

–基於多表創建視圖
create view v_test as select e.c_name,e.hiredate,e.salary,d.dname,d.location from employee e,dept d where e.department_id=d.department_id;

select * from v_test
±-------±-----------±-------±-------------±---------+
| c_name | hiredate | salary | dname | location |
±-------±-----------±-------±-------------±---------+
| 劉一 | 1980-12-17 | 7902 | 財務部 | 北京 |
| 陳二 | 1981-02-20 | 7698 | 銷售部 | 廣州 |
| 張三 | 1981-02-22 | 7698 | 銷售部 | 廣州 |
| 李四 | 1981-04-02 | 7839 | 研發部 | 上海 |
| 王五 | 1981-09-28 | 7698 | 行政部 | 深圳 |
| 趙六 | 1981-05-01 | 7839 | 人力資源 | 惠州 |
±-------±-----------±-------±-------------±---------+

–(1)使用alter table 語句創建索性,使用場景是在表創建完畢之後再添加索引。語法如下:
alter table 表名 add 索引類型 (unique,primary key,fulltext,index)[索引名](字段名)

– 普通索引(當column_list有多個的時候使用逗號隔開)
alter table table_name add index index_name (column_list) ;

– 唯一索引(當column_list有多個的時候使用逗號隔開)
alter table table_name add unique (column_list) ;

–主鍵索引(當column_list有多個的時候使用逗號隔開)
alter table table_name add primary key (column_list) ;

– (2)使用create index語句對錶增加索引,create index可用於對錶增加普通索引或UNIQUE索引,可用於建表時創建索引。
create index index_name on table_name(username(length));

– create只能添加這兩種索引;
create index index_name on table_name(column_list);
create UNIQUE index index_name on table_name(column_list);
create index index_employee on employee(salary,hiredate,c_name);

– (3)刪除索引,刪除索引可以使用ALTER TABLE或DROP INDEX語句來實現。
drop index index_name on table_name ;
alter table table_name drop index index_name ;
alter table table_name drop primary key ;
視圖
是一個虛擬表(非真實存在),其本質是【根據SQL語句獲取動態的數據集,併爲其命名】,用戶使用時只需使用【名稱】即可獲取結果集,並可以將其當作表來使用,使用視圖時,將其當作表進行操作即可,由於視圖是虛擬表,所以無法使用其對真實表進行創建、更新和刪除操作,僅能做查詢用。
索引
數據庫中將數據整齊的排列在磁盤陣列中,當獲取數據的時候只需要逐個搜索,並返回結果,但是 如果開發的應用有幾百上千萬甚至億級別的數據,那麼不深入瞭解索引的原理, 寫出來程序就根本跑不動,光查一個數據庫就得好幾天,因此就需要索引,能夠快速的查找的需要的數據。
mysql連接查詢

內連接:
等值連接
非等值連接
外連接:
左外連接:
右外連接:
自連接
– 內連接
select e.c_name,d.dname,d.location from employee e inner join dept d on e.department_id= d.department_id;
±-------±---------±--------+
| c_name | dname | location |
±-------±---------±--------+
| 劉一 | 財務部 | 北京 |
| 陳二 | 銷售部 | 廣州 |
| 張三 | 銷售部 | 廣州 |
| 李四 | 研發部 | 上海 |
| 王五 | 行政部 | 深圳 |
| 趙六 | 人力資源 | 惠州 |
±-------±---------±--------+

– 左外連接,是指以左邊的表的數據爲基準,去匹配右邊的表的數據,如果匹配到就顯示,匹配不到就顯示爲null
– 查詢employee表中的所有數據和dept表中與employee中相匹配的數據,若是沒有匹配的就顯示null
select e.c_name,d.dname from employee e left outer join dept d on d.department_id = e.department_id ;

– 修改employee中的數據
update employee set department_id=60 where employee_id=3;

– 重新查詢,由於dept表中不存在60的數據,所以再dept表中沒有對應的匹配數據,顯示爲null
select e.c_name,d.dname from employee e left outer join dept d on d.department_id = e.department_id ;
±-------±---------+
| ename | dname |
±-------±---------+
| 劉一 | 財務部 |
| 陳二 | 銷售部 |
| 張三 | NULL |
| 李四 | 研發部 |
| 王五 | 行政部 |
| 趙六 | 人力資源 |
±-------±---------+

– 右外連接和左外連接只不過是左右表相換也能達到同樣的效果
– 這裏就是查詢dept部門表對應所有部門和employee表中與之對應的數據,你會發現本來employee中有6條數據,只顯示了5條數據,因爲有一個人的部門60再dept中沒有數據,所以就沒有顯示出來。
select e.c_name,d.dname from employee e right outer join dept d on d.department_id = e.department_id;
±-------±---------+
| ename | dname |
±-------±---------+
| 劉一 | 財務部 |
| 陳二 | 銷售部 |
| 李四 | 研發部 |
| 王五 | 行政部 |
| 趙六 | 人力資源 |
±-------±---------+

– 自連接查詢就是當前表與自身的連接查詢,關鍵點在於虛擬化出一張表給一個別名
– 查詢員工以及他的上司的名稱,由於上司也是員工,所以這裏虛擬化出一張上司表
select e.c_name 員工名,b.c_name 上司名 from employee e left join employee b on e.manager_id= b.employee_id;
±-------±-------+
| 員工名 | 上司名 |
±-------±-------+
| 劉一 | 陳二 |
| 陳二 | 張三 |
| 張三 | 李四 |
| 李四 | 王五 |
| 王五 | NULL |
| 趙六 | 王五 |
±-------±-------+
mysql子連接查詢

按子查詢出現在主查詢中的不同位置分
select後面:僅僅支持標量子查詢。
from後面:支持表子查詢。
where或having後面:支持標量子查詢(單列單行)、列子查詢(單列多行)、行子查詢(多列多行)
exists後面(即相關子查詢):表子查詢(多行、多列)
– select後面的子查詢
– 查詢每個部門員工個數
SELECT d.,
(SELECT count(
)
FROM employee b
WHERE b.department_id = d.department_id)
AS 員工個數
FROM dept d;

– 查詢員工號等於3的部門名稱
SELECT
(SELECT a.dname
FROM dept a, employee b
WHERE a.department_id = b.department_id
AND b.employee_id = 3)
AS 部門名;

– from後面的子查詢
– 查詢每個部門平均工資的工資等級
– (1)先查詢每個部門平均工資
SELECT
department_id,
avg(a.salary)
FROM employee a
GROUP BY a.department_id;

– (2)然後是查詢薪資等級表
SELECT *
FROM job_grades;

– (3)將上面2個結果連接查詢,篩選條件:平均工資 between lowest_sal and highest_sal;
SELECT
t1.department_id,
avg_salary AS ‘平均工資’,
t2.grade_level
FROM (SELECT
department_id,
avg(a.salary) avg_salary
FROM employees a
GROUP BY a.department_id) t1, job_grades t2
WHERE
t1.avg_salary BETWEEN t2.lowest_sal AND t2.highest_sal;

– where和having後面的子查詢
– 查詢誰的工資比javaboy的高?
– (1)查詢lisi的工資
SELECT salary FROM employee WHERE e_name = ‘lisi’;

– (2)查詢員工信息,滿足salary>上面的結果
SELECT *
FROM employee a
WHERE a.salary > (SELECT salary
FROM employee
WHERE e_name = ‘lisi’);

–having後的子查詢
–查詢最低工資大於40號部門最低工資的部門id和其最低工資
– (1)查詢40號部門的最低工資
SELECT min(salary)
FROM employee
WHERE department_id = 40;

–(2)查詢每個部門的最低工資
SELECT
min(salary),
department_id
FROM employee
GROUP BY department_id;

–(3)③在②的基礎上篩選,滿足min(salary)>①
SELECT
min(a.salary) minsalary,
department_id
FROM employee a
GROUP BY a.department_id
HAVING min(a.salary) > (SELECT min(salary)
FROM employee
WHERE department_id = 50);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章