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
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值