zoukankan      html  css  js  c++  java
  • 数据库多表查询

    多表查询

    • 笛卡尔积查询

      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 = '技术');
      
  • 相关阅读:
    conda更换为清华镜像源
    NVDIA的GPU驱动升级
    Windows使用nvidia-smi查看GPU信息
    查询GPU是否支持CUDA
    PyTorch教程【一】Pytorch环境的配置及安装
    JAVA基础篇—继承
    SQL
    随机数
    hdu 4751 Divide Groups 二分图
    hdu 4126 Genghis Khan the Conqueror hdu 4756 Install Air Conditioning 最小生成树
  • 原文地址:https://www.cnblogs.com/luckinlee/p/11621161.html
Copyright © 2011-2022 走看看