zoukankan      html  css  js  c++  java
  • MySQL >>> 表查询

    单表查询、多表查询

    关键词: select   distinct    from    where   group by   having   order by   limit 

           inner join    left join    right join

    1. 单表查询

      前期表准备:

    # 创建表
    create table emp(       id int not null unique auto_increment,       name varchar(20) not null,       sex enum('male','female') not null default 'male', #大部分是男的       age int(3) unsigned not null default 28,       hire_date date not null,       post varchar(50),       post_comment varchar(100),       salary double(15,2)            ); # 插入记录 # 三个部门:教学,销售,运营 insert into emp(name,sex,age,hire_date,post,salary) values        ('jason','male',18,'20170301','张江第一帅形象代言',7300.33), #以下是教学部        ('egon','male',78,'20150302','teacher',1000000.31),        ('kevin','male',81,'20130305','teacher',8300),        ('tank','male',73,'20140701','teacher',3500),        ('owen','male',28,'20121101','teacher',2100),        ('jerry','female',18,'20110211','teacher',9000),        ('nick','male',18,'19000301','teacher',30000),        ('sean','male',48,'20101111','teacher',10000),        ('歪歪','female',48,'20150311','sale',3000.13),#以下是销售部门        ('丫丫','female',38,'20101101','sale',2000.35),        ('丁丁','female',18,'20110312','sale',1000.37),        ('星星','female',18,'20160513','sale',3000.29),        ('格格','female',28,'20170127','sale',4000.33),        ('张野','male',28,'20160311','operation',10000.13), #以下是运营部门        ('程咬金','male',18,'19970312','operation',20000),        ('程咬银','female',18,'20130311','operation',19000),        ('程咬铜','male',18,'20150411','operation',18000),        ('程咬铁','female',18,'20140512','operation',17000);

       创建完以后如下所示:

      

    1.1 from

      基本查询语句:需要指定表,关键字 from

        select id, name from emp;       # 结果如下:

        

    1.2 where 

      约束条件

      例子用法:

      # 1.查询 id 大于等于 3 小于等于 6 的数据
        select id, name from emp where id >= 3 and id <= 6;     # 与下面的 sql 语句等价
        select *  from emp where id between 3 and 6;   # 结果如下:

        

      # 2.查询薪资是 20000 或者 18000 或者 17000 的数据

         select * from emp where salary = 20000 or salary = 18000 or salary = 17000;  

            # 与下面的 sql 语句等价
         select * from emp where salary in (20000,18000,17000);     #结果如下:

        

      # 3.查询员工姓名中包含 o 字母的员工姓名和薪资

        select name, salary from emp where name like '%o%';   

        %可以匹配多个字符        # 结果如下:

        

      # 4.查询员工姓名是由四个字符组成的员工姓名与其薪资

        select name, salary from emp where name like '____';     #   与下面的 sql 语句等价

        一个_下划线匹配一个字符,四个就固定匹配4个
        select name, salary from emp where char_length(name) = 4;       #   结果如下

       

      # 5.查询 id 小于 3 或者大于 6 的数据

        select * from emp where id < 3 or id > 6;         #   与下面的 sql 语句等价

        select *  from emp where id not between 3 and 6;    #    结果如下:

        

      # 6.查询薪资不在 20000,18000,17000 范围的数据

        select * from emp where salary not in (20000,18000,17000);       #   结果如下:

          

       # 7.查询岗位描述为空的员工名与岗位名

        select name, post from emp where post_comment = NULL;         #    报错  Empty set (0.00 sec)

                      针对 null 不能用等号,只能用 is

        select name, post from emp where post_comment is NULL;     #   结果如下

        由于在添加记录的时候所有 post_comment 都是 null ,所以全部都匹配到了

         

    1.3 group by

      数据分组,后面接分组依据(字段名)

      例子用法:

      # 1.按部门分组

        select * from emp group by post;     # 分组后取出的是每个组的第一条数据

        

        不应该在去取组里面的单个元素的值,那样的话分组就没有意义了,因为不分组就是对单个元素信息的随意获取

        设置 sql_mode 为 only_full_group_by ,意味着以后但凡分组,只能取到分组的数据

        set global sql_mode="strict_trans_tables,only_full_group_by";     # 重新链接客户端

        

        再次尝试:select * from emp group by post;    # 报错

        

        # 强调:只要分组了,就不能够再“直接”查找到单个数据信息了,只能获取到组名

      # 2.获取每个部门的最高工资

        select post, max(salary) from emp group by post;

        

         # 每个部门的最低工资

         select post, min(salary) from emp group by post;

         

       # 每个部门的平均工资

         select post, avg(salary) from emp group by post;

        

       # 每个部门的工资总和

        select post, sum(salary) from emp group by post;

        

       # 每个部门的人数

        select post, count(id) from emp group by post;

        # count() 里面的参数可以是任意不为Null的字段名,一般我们使用 id 这个主键来进行计数

        

        以上的 max min avg sum count 都是聚合函数   >>>  聚合查询(聚集到一起合成为一个结果)

                                 以组为单位统计组内数据

       # 3.查询分组之后的部门名称和每个部门下所有的学生姓名

        # group_concat(分组之后用不仅可以用来显示除分组外字段还有拼接字符串的作用    支持同时选择多个

        select post, group_concat(name,": ",salary) from emp group by post;

        

      # 4.补充 concat(不分组时用)拼接字符串达到更好的显示效果 

        select concat("NAME: ",name) as '姓名',concat("SAL: ",salary) as '薪资'  from emp;

        

      # 5. 补充as语法       即可以给字段起别名也可以给表起

        select emp.id, emp.name from emp as t1;    # 报错  因为表名已经被你改成了t1

        select t1.name as '优秀学生名字', t1.salary as '薪资' from emp as t1 where id = 3;

        

      # 6.查询四则运算

        # 查询各个部门每个人的年薪
         select post, group_concat(name,':',salary*12) from emp group by post;
         select post as '部门', group_concat(name,':',salary*12) as '年薪' from emp group by post;
         # as可以省略,但是不推荐

         

      # 7.统计各部门年龄在30岁以上的员工平均工资

        select post, avg(salary) from emp where age > 30 group by post;
        # 对where过滤出来的虚拟表进行一个分组          结果如下:

        

    #### 练习题
    
    ```mysql
    # 刚开始查询表,一定要按照最基本的步骤,先确定是哪张表,再确定查这张表也没有限制条件,再确定是否需要分类,最后再确定需要什么字段对应的信息
    
    1. 查询岗位名以及岗位包含的所有员工名字
    2. 查询岗位名以及各岗位内包含的员工个数
    3. 查询公司内男员工和女员工的个数
    4. 查询岗位名以及各岗位的平均薪资
    5. 查询岗位名以及各岗位的最高薪资
    6. 查询岗位名以及各岗位的最低薪资
    7. 查询男员工与男员工的平均薪资,女员工与女员工的平均薪资
    """
    参考答案:
    select post,group_concat(name) from emp group by post;
    select post,count(id) from emp group by post;
    select sex,count(id) from employee group by sex;
    select post,avg(salary) from emp group by post;
    select post,max(salary) from employee group by post;
    select post,min(salary) from employee group by post;
    select sex,avg(salary) from employee group by sex;
    """

       小结: 关键字 where     group by 同时出现的情况下,group by 必须在 where 之后
           where 先对整张表进行一次筛选,然后group by再对筛选过后的表进行分组
           如何验证 where 是在 group by 之前执行而不是之后;利用聚合函数,因为聚合函数只能在分组之后才能使用
             select id, name, age from emp where max(salary) > 3000;    # 报错!
             select max(salary) from emp; 
             正常运行,不分组意味着每一个人都是一组,等运行到 max(salary) 的时候已经经过 where,group by 操作了

     1.4 having

      having 的语法格式与 where 一致,只不过 having 是在分组之后进行的过滤

      即 where 虽然不能用聚合函数,但是having可以!

      #强调:having必须在group by后面使用      换而言之:必须出现 group by 以后才能使用 having
           select * from emp having avg(salary) > 10000;  # 报错

      例子用法:

      # 统计各部门年龄在 30 岁以上的员工平均工资,并且保留平均工资大于 10000 的部门

         select post, avg(salary) from emp where age >= 30 group by post having avg(salary) > 10000;

        

    1.5 distinct

      有重复 的展示数据进行 去重操作

      例子用法:select distinct post from emp;   # 结果如下:

          

    1.6 order by

      作用:排序

      例子用法:

      #1. 按照薪资升序

        select * from emp order by salary asc;         #   asc不写默认升序

        

      # 2.按照薪资降序

        select * from emp order by salary desc;    #  降序排

        

      # 3.先按照 age 降序排,在年纪相同的情况下再按照薪资升序排

        select * from emp order by age desc, salary asc;       中间是逗号!!!!不是  and

        

      # 4.统计各部门年龄在 10 岁以上的员工平均工资,并且保留平均工资大于 1000 的部门,然后对平均工资进行排序

        select post as '部门', avg(salary) as '平均工资' from emp

        where age > 10 group by post having avg(salary) > 1000 order by avg(salary) asc;

        

    1.7 limit

      限制展示条数

      例子用法:

      # 1.查询表中前三条数据

        select * from emp limit 3;     #  结果如下:

        

      # 2.查询工资最高的人的详细信息

        select * from emp order by salary desc limit 1;  

        先对薪资进行降序排列,然后取第一条数据       #  结果如下:

        

      # 3.补充用法

        select * from emp limit 10,5;

        第一个参数表示 起始位置,第二个参数表示的是 条数,不是索引位置     #    结果如下:

        

    1.8 正则

      例子:select * from emp where name regexp '^j.*(n|y)$';    

           正则匹配内容为:以j开头,以n或y结尾,中间匹配0到多个不为换行符的内容

           如:  jjjjjn   jssssssssn  jdery   jy   jn 等都可以匹配到                     #   结果如下:

         

    2. 多表查询

      前期表准备:

    #建表
    create table dep(
          id int,
          name varchar(20) 
              );
    
    create table emp(
          id int primary key auto_increment,
          name varchar(20),
          sex enum('male','female') not null default 'male',
          age int,
          dep_id int
              );
    
    #插入数据
    insert into dep values
          (200,'技术'),
          (201,'人力资源'),
          (202,'销售'),
          (203,'运营');
    
    insert into emp(name,sex,age,dep_id) values
          ('jason','male',18,200),
          ('egon','female',48,201),
          ('kevin','male',38,201),
          ('nick','female',28,202),
          ('owen','male',18,200),
          ('jerry','female',18,204);

        创建完以后如下所示:

         

    2.1 表查询

      硬盘上是多张表,到 内存 中应该把他们 拼成一张表 进行查询

      select * from emp,dep;     得不到有效信息

      # 左表一条记录与右表所有记录都对应一遍   >>>   笛卡尔积

      

       虽然不合理但是其中有合理的数据,现在我们需要做的就是找出合理的数据

      # 查询员工及所在部门的信息

        select * from emp, dep where emp.dep_id = dep.id;   

        

       # 查询部门为技术部的员工及部门信息

        select * from emp, dep where emp.dep_id = dep.id and dep.name = '技术';

        

       ####################################################

       # 将两张表关联到一起的操作,有专门对应的方法:

         1、内连接:只取两张表有对应关系的记录

          select * from emp inner join dep on emp.dep_id = dep.id;

          

         2、左连接: 在内连接的基础上保留左表没有对应关系的记录

          select * from emp left join dep on emp.dep_id = dep.id;

          

          3、右连接: 在内连接的基础上保留右表没有对应关系的记录

          select * from emp right join dep on emp.dep_id = dep.id;

          

         4、全连接:在内连接的基础上保留左、右面表没有对应关系的的记录

          select * from emp left join dep on emp.dep_id = dep.id

          union                             # 注意:这是一句话

          select * from emp right join dep on emp.dep_id = dep.id;

          

       #############################################################

     2.2 子查询

      就是将一个查询语句的 结果用括号括起来 当作另外一个查询语句的 条件 去用

      例子用法:

        # 1.查询部门是技术或者人力资源的员工信息

          select * from emp where dep_id

                   in (select id from dep where name = "技术" or name = "人力资源");

          

         # 2.每个部门最新入职的员工      #  第一次创建的表中数据

            思路:先查每个部门最新入职的员工,再按部门对应上联表查询

            select t1.id, t1.name, t1.hire_date, t1.post, t2.* from emp as t1
            inner join
            (select post, max(hire_date) as max_date from emp group by post) as t2
            on t1.post = t2.post
            where t1.hire_date = t2.max_date;

            

       

        规律:表的查询结果可以作为其他表的查询条件,也可以通过 其别名的方式 把它作为一张虚拟表去跟其他表做关联查询

      

          

  • 相关阅读:
    2017 Multi-University Training Contest
    ACM 竞赛高校联盟 练习赛 第一场
    hdu 6194 string string string(后缀数组)
    Codeforces Round #433 (Div. 1) D. Michael and Charging Stations(dp)
    Codeforces Round #433 (Div. 2) E. Boredom(主席树)
    Codeforces Round #433 (Div. 2) C. Planning(贪心)
    Codeforces Round #433(Div. 2) D. Jury Meeting(贪心)
    hdu 6191 Query on A Tree(dfs序+可持久化字典树)
    hdu 6183 Color it(线段树)
    poj 2464 Brownie Points II(扫描线)
  • 原文地址:https://www.cnblogs.com/pupy/p/11390628.html
Copyright © 2011-2022 走看看