当前位置:Gxlcms > 数据库问题 > 数据库多表查询

数据库多表查询

时间:2021-07-01 10:21:17 帮助过:11人阅读

多表查询

  • 笛卡尔积查询

    select * from 表一,表二;
    '''
    上面这个语句的执行是想查出来两张表中所有的数据,但是发现执行结果多出来好多数据,当联表查询的时候,mysql不知道如何连接两孩子那个表的关系,也不知道你想要查询那些数据,mysql就会将两张表中所有可能组合起来的数据,全部组合起来返回给你,当然这样的好处是,帮你把所有可能的组合都做好,方便查询数据,但是效率慢,
    '''
    select * from emp,dep;#将两张表拼在一起
    select * from emp,dep where dep.id = emp.dep_id; #找到两张表中对应的关系记录
    select emp.name from dep,emp where dep.id = emp.dep_id and dep.name='技术';
    #拿到筛选后的技术部门数据中emp.name的数据
  • inner join on 内连接

    '''
    在写sql语句的时候,让我们对语句有一个清晰的区分,增强代码的可读性,联表的操作和查询的操作有个明确的区分,就用到了内连接,左链接,右链接的方式inner join on就是内连接的意思,内连接的方式就一个弊端就是,当两个表的数据中无法通过联表指定的字段对应上的时候,就无法显示这些数据,类似集合中交集的意思,
    '''
    第一步:连表
      select * from dep inner join emp on dep.id=emp.dep_id;
    第二步: 过滤
      select * from dep inner join emp on dep.id=emp.dep_id where dep.name='技术';
    第三步:找对应字段数据
      select emp.name from dep inner join emp on dep.id=emp.dep_id where dep.name='技术';
  • left join on 左连接(外连接)

    '''
    左连接的意思就是在内连接的基础上增加左边有,右边没有的数据,将左边的表作为主表,右边的表作为辅表,当辅表的数据没办法对应上左表的数据时,就通过null来表示(把左表的所有数据都显示)
    '''
    select * from dep left join emp on dep.id=emp.dep_id;
  • right join on 右链接(外连接)

    '''
    右连接于左连接的用法使一样的,不过右连接是将右表作为主表,左表作为辅表
    '''
    select * from dep right join emp on dep.id=emp.dep_id;
  • union 全连接

    '''
    不管是内连接还是左连接,右连接,都会由一些数据使无法显示出来的,那么就可以用全连接的方式来链接,写法是写一个左连接,一个右链接,中间用union 来连接
    '''
    select * from dep left join emp on dep.id=emp.dep_id union select * from dep right join emp on dep.id=emp.dep_id;
  • 子查询

    '''
    子查询是将一个查询的结果作为另一个查询的条件
    '''
    select name from emp where dep_id = (select id from dep where name = '技术');

数据库多表查询

标签:区分   第一步   就会   union   HERE   一个   可读性   一起   inner   

人气教程排行