1. 程式人生 > >mysql筆記整理

mysql筆記整理

SQL:


分類:
1. DML:instert  delete  update select  
2. DDL:create alter drop rename truncate
3. DCL:grant revoke
大小寫不敏感




mysql軟體:
1.登入:
mysql -u root -p
ENTER PASSWORD:root


完整的登入命令:
mysql -u root -h 127.0.0.1 -P 3306 -p dbname
enter password:


明文登入:
mysql -uroot -proot


指定資料庫名:
mysql -u root -p dbname
enter password:


2.登出
exit




3.檢視  db
mysql>show dadtabases;


4.進入db:
use dbname
當前資料庫名稱顯示:
show tablesroo
show processlist;




5.檢視table
show tables;


表結構的兩種方法: show columns from tbname;
  desc tbname;
表的建造過程:show create table tbname;




*** SQL
DDL:create alter drop rename truncate
資料型別:整型、浮點、字元、二進位制、布林。。。。
6.檢視具體表:
select * from table;




insert delete update select
****
7.系統檢視
show processlist;
show status;
show variable;
my.ini  my.cnf
set max_connections=1;
show table status;
8.模糊查詢 like ''
萬用字元   % 代表不確定的多個字元
_ 代表不確定的單個字元
場景:
show stataus like '';
show variables like '';
show dabases like '';
show tables like '';
select .. where … like '';




9.簡單的SELECT
select 1+2;
select 11,1+2,'aa',host from user;
select 1+2 as name;
select sleep(20);
10.mysql設定字符集統一:
set names utf8;




Datatype:
建立物件的時候會使用合適的datatype
1byte = 8bit 
1KB=1024B
1MB=1024KB
1GB=1024MB
1TB=1024GB




1個數字=1個字元
1個字母=1個字元
1個漢字=1個字元


mysql(utf8):
1個數字=1個位元組
1個字母=1個位元組
1個漢字=3個位元組




tinyint 1個位元組   0~255無符號整型
-128~127 有符號整型
smallint 2個位元組
mediumint 3個位元組
int 4個位元組
bigint 8個位元組


create table tbname(age int(4) unsigned zerofill);
insert into tbname values(11);




















===================================
DDL:create alter drop rename truncate
OBJECT:table index view program unit




1.database
create database if not exists dbname;
drop database  if exists dbname;
2.table
create table tbname(列名1 dt1, 列名2 dt2);
create table t1(age int,gender enum(‘0',‘1'));




create table tbname(列名1 dt1 列的約束條件, 列名2 dt2)table_option;
create [temporary] table [if not exists] tbname(列名1 dt1 列的約束條件, 列名2 dt2)table_option;




1.temporary 臨時表
CREATE TEMPORARY TABLE `t2` (
 `age` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1




2.if [not] exists:重要,批量資料、程式資料在處理時經常使用
create table if not exists t1(age int);
create table if not exists t1(age int);






3.table_option
()engine=innodb;
()default charset=utf8;
()auto_increment=1;
() engine=myisam default charset=gbk;




create table t3(name char(10)) default charset=gbk;
insert into t3 values('張三');
select * from t3;




4.列的約束條件
(1)NULL/NOT NULL:
create table t_null(age int,name char(10) null);
create table t_notnull(age int not null,name char(10) not null);




mysql> create table t_notnull(age int not null,name char(10) not null);
mysql> insert into t_notnull values(10,'zs');
mysql> insert into t_notnull(age) values(20);
mysql> insert into t_notnull(name) values('ls');
mysql> select * from t_notnull;




(2)DEFAULT:預設值   與NOT NULL搭配,要一直使用
create table t_default(age int not null default 1,name char(10)  default ‘briup' not null);
mysql> create table t_default(age int not null default ‘1',
    -> name char(10) default 'briup' not null);
mysql> show create table t_default;
| t_default | CREATE TABLE `t_default` (
  `age` int(11) NOT NULL DEFAULT '1',
  `name` char(10) NOT NULL DEFAULT 'briup'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
mysql> insert into t_default values(2,'zs');
mysql> insert into t_default(age) values(3);
mysql> insert into t_default(name) values('ls');
mysql> select * from t_default;
+-----+-------+
| age | name  |
+-----+-------+
|   2 | zs    |
|   3 | briup |
|   1 | ls    |
+-----+-------+
3 rows in set (0.00 sec)




(3)unique:唯一性
create table t_unique(age int not null default ‘1',
name char(10)  unique);
列的唯一:行級約束
create table t_unique(
name char(10) unique,
qq char(10) unique,
age    int);
聯合唯一:表級約束
create table t_unique(
name char(10),
qq char(10),
age    int,
unique(name,qq) );


zs 123
zs 234  error
ls 123error
ls 234
[zs 123]








(4)primary key 主鍵:非空唯一索引
一個表中只能有一個主鍵
create table t_pk(
id int primary key,
name char(10));
create table t_pk(
id int,
name char(10),
primary key(id));
行級約束、表級約束
create table t_pk(
id int,
stuno int,
name char(10),
primary key(id,stuno));




(5)auto_increment:自增
條件:必須是主鍵或者非空唯一索引列
1.從1開始計數
2.以實際插入資料為準
3.以全文最大值加1
create table t_pk(
id int primary key auto_increment,
name char(10));
create table t_pk(
id int primary key auto_increment,
name char(10))auto_increment=1000;




(6)foregin key外來鍵:外表
primary key 主鍵:主表
商品表 
編號 名稱單價格 庫存量
id nameprice num
1001 dress200 20
1002 cloth100.5 10




購物車表
編號   商品編號購買量
cartid goodid buynum
1 10013
2 10021








主表:商品表 先決條件
create table if not exists good(
id int primary key auto_increment, 
name varchar(20) not null default '',
price float(11,2) not null default '0.00',
num int unsigned not null default '0'
)engine=innodb default charset=utf8 auto_increment=1001;




外表:購物車表 外來鍵依賴關係:表級約束
create table if not exists cart(
cartid int primary key auto_increment, 
goodid int,buynum int unsigned not null default '0',
foreign key(goodid) references good(id)
)engine=innodb default charset=utf8;




條件:
1.先有主表,後有外表
2.外表中的資料依賴主表而存在
3.主表中的資料可以不在外表中出現
4.外表中可以存在多條(0,1,N)主表的資料
5.外表一定要有innodb引擎
6.外表中的外來鍵要去關聯的是主表的主鍵
7.一般主鍵和外來鍵的資料型別要一致




列的約束條件 行級約束 表級約束 聯合
NOT NUL/NULL   YN N
DFAULT  '' Y N N
UNIQUE Y Y Y
PK Y YY
FK N YY
auto_increment YN N
index N Y Y OBJECT
key Y(pk) Y(index)




(7)索引
主表:商品表 先決條件
create table if not exists good(
id int primary key auto_increment, 
name varchar(20) not null default '',
price float(11,2) not null default '0.00',
num int unsigned not null default '0'
)engine=innodb default charset=utf8 auto_increment=1001;


create table g1(id int primary key key,name varchar(20));
create table g2(id int primary key,name varchar(20) key);//error
create table g2(id int ,name varchar(20) key);//primary key
create table g3(id int primary key,name varchar(20),key(name));//key
create table g4(id int, name varchar(20),key(name));//key
create table g5(id int primary key,name varchar(20),key(id,name));//key




create table gg1(id int  index,name varchar(20));//error
create table gg3(id int primary key,name varchar(20),index(name));//key
create table gg5(id int primary key,name varchar(20),index(id,name));//key




create index idname on tbname(columnname);
create view vname as select ….;  檢視、望遠鏡,資料還是存在在原來的地方








綜合需求:建立兩張表,一張為學生資訊表,一張為學生成績表
資訊表:student_info
編號:id int 自增,從10000開始
姓名:name varchar(20)非空
性別:gender enum,取值為(0,1),非空--0表示男生,1表示女生
年齡:age tinyint unsigned非空
學號:number int,非空唯一索引
create table if not exists student_info(
id int auto_increment primary key,
name varchar(20) not null default '',
gender enum(‘0','1') not null default ‘0',
age tinyint unsigned not null default ‘0'
number int not null defalt ‘0'unique,
unique(number),
key(number),
index(number)
)engine=innodb default charset=utf8 auto_increment=10000;
create index idnum on student_info(number);




成績表:student_mark
編號:id int 自增,從1開始
科目:mark_name varchar(25) 非空
成績:mark int 非空非負數預設值為0
學號:stu_no外來鍵關聯資訊表中的學生number列
create table if not exists student_mark(
id int auto_increment primary key,
primary key(id),
mark_name varchar(25) not null default '',
mark int unsigned not null defualt ‘0',
stu_no int ,
foreign key(stu_no) references stu_info(number)
)engine=innodb default charset=utf8;








要點:由於兩張表有聯絡,存在外來鍵約束,需要使用innodb,在table_option設定
設定自增的起始值需要在table_option設定
多個table_option用空格分隔
自增約束的列需要是主鍵
列舉需要引號,即使要表達數值的含義,也要使用引號
預設值需要單引號,如果要表達數值的含義,也推薦使用引號








二、ALTER
語法:ALTER [IGNORE] TABLE tbl_name alter_spec [, alter_spec ...] 
help alter table;




1. 建立一張alter_test表,列id int      create table alter_test(id int);
create table alter_test(id int);  
需求1:往alter_test表中增加一列name varchar(20) 非空唯一  
目的:增加列
解決:alter table alter_test
add column name varchar(20) not null unique;




需求2:將name列設定為索引列,索引名字為name_index  
目的:增加索引
解決:create index name_index on alter_test(name);
alter table alter_test add index name_index(name);




需求3:將id列設定為主鍵列  
目的:增加主鍵
解決:alter table alter_test add primary key(id);




需求4:往alter_test表中先增加一列no int,然後用alter語句更新表中的no列,加上唯一約束。
目的:增加唯一性  
解決:alter table alter_test add column no int;
alter table alter_test add unique(no);








需求5:將name列的預設值設定為'aaa'  
目的:單獨修改已經存在列屬性:新增預設值
解決:alter table alter_test alter column name set default ‘aaa';








需求6:將name的預設值刪除  
目的:單獨修改已經存在列屬性:刪除預設值
解決:alter table alter_test alter column name drop default;




change和modify都能夠對已經存在的列進行修改,不同的是change可以重新命名列,modify不能。 
===========================
面試常考:
注意:用change和modify的時候會將原來的約束覆蓋,因此可以通過show create table tb_name獲得原有的約束,
一定要將原有的約束原封不動的加上,不然會丟失。




=========================== 
需求7:將no列修改成alter_test_no int(20) not null unique. 
目的:整體修改已經存在列屬性(同時重新命名列) 
解決:alter table alter_test change no  【alter_test_no int(20) not null unique】;
解決:alter table alter_test change alter_test_no  no int(20) not null;








需求8:將alter_test_no列修改成int(21) not null unique  
目的:整體修改已經存在列屬性
解決:alter table alter_test modify 【alter_test_no int(21) not null unique】;








需求9:刪除alter_test_no列  
目的:刪除列
解決:alter table alter_test drop column alter_test_no;




需求10:刪除name列的索引約束  
目的:刪除索引
解決:drop index name_index on alter_test;
alter table alter_test drop index name_index;




需求11:刪除id的主鍵約束  
目的:刪除主鍵
解決:alter table alter_test drop primary key;




需求12:將表的名字alter_test改成alter_test2  
目的:修改表名
解決:rename table alter_test to alter_test3;
alter table alter_test3 rename  alter_test2;








需求13:將表alter_test2的資料引擎改成myisam
目的:修改資料引擎
解決:alter table alter_test2 engine=myisam default charset=utf8;




















2.建立一張alter_test表,列id int      
create table alter_test(id int); 
 插入重複資料 insert into ai_test values(1),(1),(1),(2),(3); 
需求14:將id列設定為主鍵列  
目的:去重複資料,增加主鍵
解決:alter ignore table alter_test add primary key(id);




3.怎樣增加外來鍵約束?  
步驟:首先將涉及到的表引擎設定成innodb  
     然後新增外來鍵約束:alter table alter_test add foreign key(current_col_name) references primary_tb_name(primary_key_col_name); 
實現:建立兩張表
create table alter_test_pk(id int);  
create table alter_test_fk(id int primary key,fk_id int); 
需求15:將alter_test_fk中的fk_id列外來鍵關聯alter_test_pk表中的id列  
alter table alter_test_pk add primary key(id);
alter table alter_test_pk engine=innodb;
alter table alter_test_fk engine=innodb;
//select 資料的一致性/不能夠種類fk>pk
alter table alter_test_fk add foreign key(fk_id) references 
alter_test_pk(id);








需求16:將alter_test表重新命名alter_test2
解決:




注意: 使用ALTER TABLE要極為小心,應該在進行改動前做一個完整的備份(模式和資料的備份)。dump  source
資料庫表的更改不能撤銷,如果增加了不需要的列,可能不能刪除它們。
類似地,如果刪除了不應該刪除的列,可能會丟失該列中的所有資料。








DDL:create drop銷燬 alter rename truncate清空
database:
create databse dbname;
drop database dbname;
Table
create table tbname(列名 資料型別 約束條件,….);
drop table tbname;
alter…..
rename table old_tbname to new_tbname;
truncate tbname;
index
create index index_name on tbname(columnname);
drop index index_name on tbname;
View
create view view_name as select ….;
drop view view_name;




DML:insert delete刪除消除 update select
Insert:
insert into tbname values(1,'zs',20);
一條資料插入:【insert into tbname(name,id) values(‘zs',1);】
多條資料插入:【insert into tbname(name,id) 
values(‘zs',1),(‘ls',2),(….),(….);】
1.插入的資料的個數要與指定列的個數相同
2.插入的資料的順序要與指定列的順序相同
3.如果沒有指定列,要與show create的順序和個數完全相同
4.插入的資料要與對應的列的資料型別一致
Delete:
比較drop/truncate/delete的區別
delete from tbname;




select * from tbname where age=1 and weight>=2;
delete from tbname where 【 age=1 and weight>=2】;
if(age==1 and weight>=2){宰了}




Update:修改
select age from tbname  where id=1;
update tbname set age=100 where id=1;




update tbname set age=10 where id<2;
update tbname set id=10 where id<2;




select id,age from t11 where id<2;
update t11 set id=10 , age=10 where id<2;




update t11 set age=age+1;
















============================
Where age between 1 and 3;
Where age>=1 and age<=3;
Where age not between 1 and 3;
Where age<1 or age>3;












Sss….
Ssdgegrhrhhr




====================================================================================








亂碼:UTF8
1.程式碼設定字符集UTF8
set names utf8;
create default charset=utf8;
2.source C:/workplace/test/briup.sql;








Select :查詢
1.簡單語法:
select * from tbname;//*:指代所有列,所有列的列名的簡寫
select colname1,colname2,colname3 from tbname;//選擇出指定的列
2.完全語法:
select distinct colname1,colname2…
from tbname
where ….
group by …
having….
order by…
limit …




1.select 修飾的:
a)常量:運算、時間 select 1+1,id,name from tbname;
b)  函式:concat()
select id,concat(last_name,'\'',first_name) from s_emp;
    ifnull(colname,value)
select id,last_name,ifnull(salary,0) from s_emp;




case colname
when value then newvalue
when value1 then newvalue1
when value2 then newvalue2
else newvalueN
end




switch(colname){
case ‘value': colname=newvalue;
break;
case ‘value1':colname=newvalue1;
break;
default:
colname=newvalueN;


}




select id,case name when 'Asia' then 'newAsia'
when 'Europe' then 'newEurope' else name  end from s_region;
c)重新命名列/重命名錶
select colname as newname ,colname newname from tbname;
select id,name,2017 as year ,1+1 sum from s_region;
select id,name ,date_format(now(),'%Y/%m/%d %H:%i:%s') as date from s_region;
select id,concat(last_name,'\'',first_name) as name from s_emp ;
select id,last_name,ifnull(salary,0) salary  from s_emp;
select id,case name when 'Asia' then 'newAsia' when 'Europe' then 'newEurope' else name end  as name  from s_region;




select s_region.id,s_region.name from briup.s_region;
select r.id,r.name from briup.s_region as r;
select r.id,r.name from briup.s_region  r;




d)distinct:唯一、剔除重複資料
select distinct dept_id from s_emp;
select distinct colname1,colname2,colname3 from s_emp;




需求:每個員工月工資加100後的年薪是多少?
select id,last_name , (salary+100)*12 as yearsalary
from s_emp;
2.where :篩選、限制
select … from .. where age=1 and id>4;
where 【colname 比較操作符 value】邏輯連線符
【colname1 比較操作符 value】邏輯連線符
【 colname1 比較操作符 value】;
a)比較操作符:
>,>=,<,<=,!=,=,<=>,<>
<>,!=,=判斷是否相等:數值、字串
<=>:判斷是否為NULL值
is null 判斷NULL值相等
is not null判斷NULL值不等
select * from s_region where name='Asia';
select id,last_name,salary from s_emp where salary<=>null;
b)邏輯連線符號:
AND   && 高
OR ||低
NOT 最高
select id,last_name,salary from s_emp where salary>500 and salary<1000;
select id,last_name,salary from s_emp where salary>500 or salary<1000;
c)like:模糊查詢
not like:
符號:%:0到多個任意字元
 _:一個字元
 \:轉義符號
需求:查詢名字以字母c開頭的員工有哪些
select id,last_name from s_emp where last_name  like ‘c%';
create table t1(name varchar(10) binary);
select id,last_name from s_emp where binary last_name like 'c%';
需求:查詢員工的職位是五個字元以上的員工
select id,last_name,title from s_emp where title like ‘______%';
需求:查詢客戶名稱有特殊符號'的客戶有哪些
select id,name from s_customer where name like ‘%\'%';
select id,name from s_customer where name not like ‘%\'%';
d) colname between  value1 and value2:閉區間
colname not between  value1 and value2:開區間
select id,last_name,salary from s_emp where salary between 500 and 800;
select id,last_name salary from s_emp where salary>=500 and salary<=800;
select id,last_name,salary from s_emp where salary not between 500 and 800;
select id,last_name salary from s_emp where salary<500 or salary>800;
e)in(v1,v2,v3)in(selec….)
not in (v1,v2,v3)
select id,last_name,salary from s_emp where salary=700 or salary=750 or salary=800;
select id,last_name,salary from s_emp where salary in (700,750,800);
select id,last_name,salary from s_emp where salary not in (700,750,800);
select * from s_region where name  not in ('Asia','europe');
select * from s_region where name !=‘Asia' and  name !=‘Europe';


需求:檢視部門ID為41,且職位名稱為stock_clerk的員工ID,姓名和薪資
select id,last_name,salary,dept_id,title
from s_emp
where dept_id=41
and title=‘stock_clerk'
練習:檢視44號部門薪資大於1000或者42號部門薪資小於2000的員工ID,姓名
select id,last_name,dept_id,salary
from s_emp
where (dept_id=44 andsalary>1000)
or ( dept_id=42 and salary<2000)




3.group by colname, colname2:分組:以colname作為依據進行分組
 having ….  :篩選、限制分組後的資料
分組的概念->資料:組函式、組資料,error(個體資料)
組函式
1.統計每個部門的員工總數
select dept_id,count(*),id//errror
from s_emp 
group by dept_id
2.統計該公司總人數






需求:檢視每個部門的員工數,count(*)合計函式,返回行的總數
需求:統計不由11號和12號員工負責的客戶的人數
select count(*)
from s_customer
where sales_rep_id not in(11,12) or sales_rep_id is null;


需求:檢視每個部門的平均工資
select dept_id,count(*),avg(salary),sum(salary*12),max(salary),min(salary)
from s_emp group by dept_id;




需求:檢視每個部門的每年支出薪資
需求:檢視每個部門的最高工資
需求:檢視每個部門的最低工資
需求:查詢每個部門相同職位的員工的平均工資
select dept_id,tittle,aavg(salary) from s_emp
group by dept_id,title;




需求:檢視平均工資大於2000的部門id
select dept_id,avg(salary) as avgs
from s_emp
group by dept_id
having avg(salary)>2000








需求:檢視部門員工數大於2的部門id
select dept_id,count(*) as number
from s_emp
group by dept_id
having count(*)>2;












需求:檢視部門總月薪大於2000的部門id,且按照部門月薪進行降序排序
select dept_id,sum(salary) as sums
from s_emp
group by dept_id
having sum(salary)>2000
order by sums desc;
需求:檢視部門總月薪大於2000的部門id,且部門員工不包括以VP職位名稱開頭員工,最後按照部門月薪進行降序排序
select dept_id,sum(salary) as sums
from s_emp
where title not like ‘VP%'
group by dept_id
having sum(salary)>2000
order by sums desc;




error:
select dept_id,sum(salary) as sums from s_emp  group by dept_id having sum(salary)>2000 and title not like 'VP%'  order by sums desc;












排序 
order by colname [asc]預設升序
order by colname desc降序
order by colname1 [asc],colname2 [asc];








需求:檢視員工的員工ID,名字,月薪,按照月薪的降序排序。
練習:檢視員工的員工ID,名字,月薪,部門ID,部門ID進行升序排序,相同部門的員工在一起按照薪資從高到低排序




Limit N:限制最終顯示的條數




分頁操作:
limit start,len;
start:從0 開始計數




1: 1~5limit 0,5;
2: 6~10limit 5,5;
3: 11~15limit 10,5;
4 limit 15,5;
page start=(page-1 )*every








==========================================================================
1.SUBQUERY-1:子查詢可以作為父查詢的篩選的依據
select ….
from …
where colname 比較操作符 (select .. from ..where ..group by ..having…order by..limit..)
group by …
having 組函式 比較操作符(select .. from ..where ..group by ..having…order by..limit..)
order by …
limit …








子查詢1
需求:1.檢視職員名稱和名字為chang的員工一樣的所有員工的id和名字
a)父查詢:檢視職位名稱和名字=xxx的所有員工的id和名字
select id,last_name,title from s_emp where title=???
b)子查詢:名字為chang的員工的title
select title,last_name from s_emp where last_name=‘Chang';
c)合併:
select id,last_name,title from s_emp where title=(
select title from s_emp where last_name=‘Chang';





需求:2.檢視員工工資小於平均工資的所有員工的id和名字
a)父查詢:檢視員工工資小於xxxx的所有員工的id和名字
select id,last_name,salary from s_emp where salary<(???);
b)平均工資
select avg(salary) as avgs from s_emp;
c)合併
select id,last_name,salary from s_emp where salary<(select avg(salary) as avgs from s_emp);




需求:3.檢視部門與員工名字為Chang的員工所在部門相同,或者與區域為2的部門相同的部門所有員工的id和名字
注意驗證子查詢的返回結果
a)父查詢:檢視部門=xx,或者與部門=xxx所有員工的id和名字
select id,last_name,dept_id from s_emp where dept_id=(xxx) or dept_id in (xxx);
b)子查詢1:名字為Chang的員工所在部門
select dept_id from s_emp where last_name=‘Chang';
c)子查詢2:區域為2的部門
select id from s_dept where region_id=2;
d)合併:
select id,last_name,dept_id from s_emp where dept_id=(select dept_id from s_emp where last_name=‘chang') or dept_id in (select id from s_dept where region_id=2);




需求:4.檢視部門平均工資大於32號部門平均工資的部門id
a)父查詢:檢視部門平均工資大於xxx的部門id
select dept_id,avg(salary) from s_emp group by dept_id having avg(salary)>1200;
b)子查詢:32號部門平均工資
select dept_id,avg(salary) from s_emp where dept_id=32;
c)合併:
select dept_id,avg(salary) from s_emp group by dept_id having avg(salary)>(
select avg(salary) from s_emp where dept_id=32
);
需求:5.檢視工資大於Smith所在部門平均工資的員工id和姓名
a)父查詢:檢視工資大於xxx的員工id和姓名
select id,last_name,salary from s_emp where salary>(??);
b)子查詢:某個部門平均工資
select dept_id,avg(salary) from s_emp where dept_id=(??);
c)子子查詢:Smith所在部門
select dept_id from s_emp where last_name=‘Smith';
d)合併:
select id,last_name,salary from s_emp where salary>(
select avg(salary) from s_emp where dept_id=(
select dept_id from s_emp where last_name=‘Smith'
)
);
練習:檢視薪資高於Chang員工經理薪資的員工資訊
select id,last_name,salary from s_emp where salary>(
select salary from s_emp where id=(
select manger_id from s_emp where last_name=‘Chang'
)
);












練習:檢視薪資高於(Chang員工經理的經理所在區域的)最低工資的員工的資訊
select id,last_name,salary from s_emp where salary>(
select min(salary) from s_emp where dept_id in (
select id from s_dept where region_id=(
select region_id from s_dept where id =(
select dept_id from s_emp where id=(
select manger_id from s_emp where id=(
select manger_id from s_emp where last_name=‘Chang'
)
)
)
)
)
);












練習:檢視所有客戶負責員工的總工資
select sum(salary) from s_emp where id in (
select distinct sales_rep_id from s_customer
);








練習:檢視工資大於客戶負責員工最高工資的員工資訊
select id,last_name,salary from s_emp where salary>(
select max(salary) from s_emp where id in (
select distinct sales_rep_id from s_customer
));




練習:檢視客戶負責員工中工資大於Chang員工的工資的員工資訊
select id,last_name,salary from s_emp where 
id in (select distinct sales_rep_id from s_customer)
and salary>(select salary from s_emp where last_name=‘Chang');








練習:檢視部門平均工資大於Chang所在部門平均工資的部門id
select dept_id,avg(salary) from s_emp group by dept_id
having avg(salary)>(select avg(salary) from s_emp where dept_id=(
select dept_id from s_emp where last_name=‘chang'
));
練習:檢視Chang員工所在部門其他員工薪資總和
select sum(salary) from s_emp where 
dept_id=(select dept_id from s_emp where last_name=‘chang')
and id!=(select id from s_emp where last_name=‘chang')




練習:查詢工資大於41號部門平均工資的員工,並且該員工所在部門的平均工資也要大於41號部門的平均工資
select id,last_name,salary,dept_id from s_emp
where salary>(select avg(salary) from s_emp where dept_id=41)
and dept_id in (select dept_id from s_emp 
group by dept_id having avg(salary)>(
select avg(salary) from s_emp where dept_id=41
));
1.SUBQUERY-2:子查詢可以作為父查詢的資料來源
select ….
from (select .. from ..where ..group by ..having…order by..limit..) as newtbname
where colname 比較操作符 (select .. from ..where ..group by ..having…order by..limit..)
group by …
having 組函式 比較操作符(select .. from ..where ..group by ..having…order by..limit..)
order by …
limit …




子查詢2 
需求:1.求平均薪水最高的部門的id
select dept_id,avg(salary)  as newsalary from s_emp group by dept_id
having avg(salary)= (




select max(newsalary) from (
select dept_id,avg(salary)  as newsalary from s_emp group by dept_id
) as newtb




);




需求:2.求平均薪水最高的部門的部門名稱
select name from s_dept where id=(
select dept_id from s_emp group by dept_id
having avg(salary)=(
select max(newsalary) from (
select dept_id,avg(salary) as newsalary from s_emp group by dept_id
) as newtb
)
);




==================================================================
等值連線
select tbname1.colname as id1 ,t2.colname as id2
from tbname1 as t1,tbname2 as t2
from tbname1 join tbname2
where  找到兩張表之間的關聯關係..
group by …
having…
order by…
limit












需求:檢視所有員工的所在部門的名稱
select s_dept.name,s_dept.id,s_emp.dept_id,s_emp.id,s_emp.last_name
from s_emp,s_dept
where s_emp.dept_id = s_dept.id


查詢平均工資大於1200的部門,並顯示這些部門的名字
1.找到涉及哪些列-》哪些表
salary ,avg(salary),dept_name,dept_id
s_emp,s_dept
2.表之間的聯絡
s_emp.dept_id=s_dept.id




3.全量的完整語法
select  d.name,e.dept_id,e.id,e.last_name,e.salary
from s_emp e,s_dept d
where e.dept_id=d.id




select  d.name,e.dept_id,avg(e.salary)
from s_emp e,s_dept d
where e.dept_id=d.id
group by e.dept_id,d.name
having avg(e.salary)>1200






練習:
檢視員工名字為Chang的員工或者工資大於1200所在的部門名稱
select s_dept.name,s_emp.id,s_emp.last_name,s_emp.salary
from s_emp,s_dept 
where s_emp.dept_id=s_dept.id
and ( s_emp.last_name=‘Chang'
or s_emp.salary>1200)






檢視所有部門的所在區域名稱
select r.name,d.name
from s_dept d,s_region r
where d.region_id=r.id




檢視所有員工的所在區域名稱
select e.id,e.last_name,d.name,r.name,e.salary
from s_emp e,s_dept d,s_region r
where e.dept_id = d.id
and d.region_id= r.id


檢視員工的id,last_name,salary,部門名字,區域名字,
這些員工有如下條件:薪資大於Chang所在區域的平均工資或者跟Chang員工不在同個部門
select e.id,e.last_name,e.salary,d.name,r.name
from s_emp e,s_dept d,s_region r
where e.dept_id = d.id
and d.region_id= r.id
and (
e.salary>(
select avg(e.salary) 
from s_emp e,s_dept d,s_region r 
where e.dept_id = d.id and d.region_id= r.id 
and r.id=(
select r.id from s_emp e,s_dept d,s_region r  
where e.dept_id=d.id and d.region_id=r.id and e.last_name='Chang')
group by d.id)
or e.dept_id !=(
select dept_id from s_emp where last_name=‘Chang'
)
); 












檢視區域工資最高的區域id和名字
select max(salary),r.id,r.name
from s_emp e,s_dept d,s_region r
where e.dept_id = d.id
and d.region_id= r.id
group by r.id,r.name




檢視部門數量最多的區域id和名字
select count(*),r.id,r.name
from s_dept d,s_region r
where d.region_id=r.id
group by r.id,r.name








檢視員工工資高於所在部門平均工資的員工的id和名字
select id,last_name,salary from s_emp where salary>(select avg(salary) from s_emp group by dept_id);//少條件




select e.id,e.last_name,e.salary,avgtb.avgs
from s_emp e,(select dept_id,avg(salary) as avgs from s_emp group by dept_id) avgtb
where e.dept_id=avgtb.dept_id
and e.salary>avgtb.avgs




查詢工資大於41號部門平均工資的員工,並且該員工所在部門的平均工資也要大於41號部門的平均工資,
顯示出當前員工所在部門的平均工資以及該員工所在部門的名字
1。平均工資表的概念:select dept_id,avg(salary) as avgs from s_emp group by dept_id
2.子查詢和等值查詢要靈活搭配使用




select e.id,e.last_name,e.salary,avgtb.avgs,d.name
from s_emp e,s_dept d,(select dept_id,avg(salary) as avgs from s_emp group by dept_id) avgtb
where e.dept_id=avgtb.dept_id and e.dept_id=d.id 
and (e.salary>(select avg(salary) from s_emp where dept_id=41)
and avgtb.avgs>(select avg(salary) from s_emp where dept_id=41)
);






查詢工資大於Ngao所在部門平均工資的員工,
並且該員工所在部門的平均工資也要大於Ngao所在部門的平均工資,
顯示出當前員工所在部門的平均工資以及該員工所在部門的名字
select avg(salary) from s_emp 
where dept_id=(select dept_id from s_emp where last_name='Ngao')


select avg(e1.salary)
from s_emp e1,s_emp e2
where e1.dept_id=e2.dept_id
and ( e2.last_name='Ngao')




select e.id,e.last_name,e.salary,avgtb.avgs,d.name
from s_emp e,s_dept d,(select dept_id,avg(salary) as avgs from s_emp group by dept_id) avgtb
where e.dept_id=avgtb.dept_id and e.dept_id=d.id 
and (e.salary>(select avg(e1.salary)
from s_emp e1,s_emp e2
where e1.dept_id=e2.dept_id
and ( e2.last_name='Ngao'))
and avgtb.avgs>(select avg(e1.salary)
from s_emp e1,s_emp e2
where e1.dept_id=e2.dept_id
and ( e2.last_name='Ngao'))
);




外連線:




select ..
from tb1 left/right [outer] join tb2
on tb1.colname=tb2.colname
where ….




外連結:希望有冗餘資料存在,資料健全不能丟失


需求:檢視客戶名以及其對應的銷售人員名
select c.name,e.last_name
from s_customer c  join s_emp e
where c.sales_rep_id = e.id;






select c.name,e.last_name
from s_customer c  left outer join s_emp e
on c.sales_rep_id = e.id;






select c.name,ifnull(e.last_name,'無銷售員')
from s_emp e  right join s_customer c
on c.sales_rep_id = e.id;
















練習:學生資訊
學生資訊表:stu_info
id int pk
name varchar(20) 姓名
1,‘zs'
2,'ls'
3,'ww'
學生成績表:stu_mark
id int pk
name varchar(20) 科目
stu_no int 外來鍵關聯資訊表中id列
mark int(3) 成績
1,'chinese',1,90
2,'math',1,90
3,'chinese',2,100
檢視所有學生的成績資訊
select stu_info.id,stu_info.name,stu_mark.name,stu_mark.mark
from stu_info left join stu_mark
on stu_info.id=stu_mark.stu_no
























================================
分組:每,各,組函式名字
面試常考知識點:外連線!
關鍵字:任何,所有,等具有全域性的對映外連線考點的關鍵字。
================================




自連線:
需求:檢視所有員工名字以及其對應的經理名字
select e.id,e.last_name,m.id,m.last_name
from s_emp e left join s_emp m
on e.manager_id = m.id




需求:subqueries中的需求5
需求:檢視員工的姓名、部門號、工資、所在部門工資排名,部門號按照升序排列,工資按照降序排列
select e1.id,e1.last_name,e1.salary,e1.dept_id ,e2.salary,e2.id,e2.last_name from s_emp e1,s_emp e2 where e1.dept_id=41
and e1.dept_id=e2.dept_id and e1.salary<e2.salary




select e2.salary,e2.id,e2.last_name,count(*) from s_emp e1,s_emp e2 where e1.dept_id=41
and e1.dept_id=e2.dept_id and e1.salary<=e2.salary
group by e2.salary;








select e2.salary,e2.id,e2.last_name,count(*) from s_emp e1 right join s_emp e2 on  e1.dept_id=e2.dept_id and e1.salary>=e2.salary
where e1.dept_id=41
group by e2.salary;
自連線:主外來鍵、普通關聯關係、其他關係
select e2.salary,e2.id,e2.last_name,count(*) as num,e2.dept_id from s_emp e1,s_emp e2 
where  e1.dept_id=e2.dept_id and e1.salary>=e2.salary
group by e1.dept_id,e2.salary
order by e2.dept_id,num;




//比如31號部門工資相同但人不一樣,group by 新增e2.last_name
select e2.salary,e2.id,e2.last_name,count(*) as num,e2.dept_id from s_emp e1,s_emp e2 
where  e1.dept_id=e2.dept_id and e1.salary>=e2.salary
group by e1.dept_id,e2.last_name,e2.salary
order by e2.dept_id,num;




//丟了一個工資為NULL的人
select e2.salary,e2.id,e2.last_name,count(*) as num,e2.dept_id 
from s_emp e1 right join s_emp e2 
on  e1.dept_id=e2.dept_id and e1.salary>=e2.salary
group by e1.dept_id,e2.last_name,e2.salary
order by e2.dept_id,num;












練習:查詢每一個管理者手下的最低工資的員工,沒有管理者的員工不算並顯示出管理者的名字
select emp.id,emp.last_name,emp.salary,manager.id,manger.last
s_emp as emp,s_emp as manager
where emp.manger_id=manager.id








select min(emp.salary),manager.id,manger.last
s_emp as emp,s_emp as manager
where emp.manger_id=manager.id
group by manger.id








select min(e.salary),e.manager_id,m.last_name from s_emp e,s_emp m
where e.manager_id is not null and e.manager_id=m.id
group by e.manager_id,m.last_name
order by e.manager_id;




練習:查詢每一個管理者手下的最低工資的員工,沒有管理者的員工也算並顯示出管理者的名字




求每個部門的平均工資
group by dept_id




select:返回結果空、一種表(列名+多條資料)
select … from … where … group by … having … order by … limit…
子查詢:篩選條件(where,having)、資料依據(from as tbname)  =>語文:外-》內 父子關係
Join查詢:
內連線查詢、等值查詢:
from tb1,tb2,tb3
from tb join tb2 join tb3
from tb1 inner join tb2 inner join tb3
外連結查詢:
from 【tb1 left join tb2 】 right join tb3
自連線查詢
from tb1,tb2
from  s_emp as tb1 left join s_emp as tb2
on tb1.manger_id=tb2.id