• MySQL多表查询


    1、多表连接查询

    2、子查询


     1、多表连接查询

     A  笛卡尔积

    select * from emp,dep;# 不使用任何匹配条件。生成笛卡尔积
    select * from emp,dep where emp.dep_id=dep.id;

    B  内连接 inner join

    内连接inner join:取两张表的共同部分

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

    C  左连接 left join

    左连接left join:在内连接的基础上保留左表的记录

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

    D  右连接 right join

    右连接right join:在内连接的基础上保留右表的记录

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

    E  全外连接 full join

    全外连接full join:在内连接的基础上保留左、右表的记录

    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;

    F  符合条件的查询

    以内连接的方式查询employee和department表,并且employee表中的age字段值必须大于25,即找出年龄大于25岁的员工以及员工所在的部门
    select employee.name,department.name from employee inner join department
        on employee.dep_id = department.id
        where age > 25;

    2、子查询 

    A  带IN关键字的子查询

    #查询平均年龄在25岁以上的部门名
    select id,name from department
        where id in 
            (select dep_id from employee group by dep_id having avg(age) > 25);
    #查看不足1人的部门名(子查询得到的是有人的部门id)
    select name from department where id not in (select distinct dep_id from employee);

    B  带比较运算符的子查询

    #比较运算符:=、!=、>、>=、<、<=、<>
    
    #查询大于所有人平均年龄的员工名与年龄
    mysql> select name,age from emp where age > (select avg(age) from emp);

    C 带EXISTS关键字的子查询

      EXISTS关字键字表示存在。在使用EXISTS关键字时,内层查询语句不返回查询的记录。而是返回一个真假值。True或False

      当返回True时,外层查询语句将进行查询;当返回值为False时,外层查询语句不进行查询

    #department表中存在dept_id=203,Ture
    select * from employee
    where exists
                 (select id from department where id=200);
  • 相关阅读:
    vmware vcenter appliance dhcp 改为 静态IP导致web service认证失败
    pptp记录用户登陆日志
    MySQL内存使用分析
    mysql慢查日志分析工具 percona-toolkit
    my.cnf详解
    ios9 升级后 企业版app plist无法安装
    redmine发送邮件
    swap文件
    算法--合法序括号序列判断
    算法--空格替换
  • 原文地址:https://www.cnblogs.com/snailgirl/p/8745992.html
Copyright © 2020-2023  润新知