zoukankan      html  css  js  c++  java
  • 关于Mysql的高级查询的操作

    前言:作为一名后端的程序员操作数据库的能力是我们基本的技能,而连表查询是我们的这个技能的关键点所在.注意这里顾明思义是对数据的查询的操作

    (一).联合查询(关键字union/union all)

      什么是联合查询:联合查询其实就是通过关键字将多条查询SQL语句连接起来。

      

    例:(select * from teacher where 1 order by days desc limit 1) union (select * from teacher where 1 order by days desc limit 1);小结[1.常用于相反的业务逻辑,2.字段要保持一致3.会去除重复]
    例:(select * from teacher where 1 order by days desc limit 1) union all (select * from teacher where 1 order by days desc limit 1);小结[1.常用于相反的业务逻辑,2.字段要保持一致3.不会去除重复]

    (二).子查询

      1.标量子查询

      概念:标量子查询就是 本条查询语句的查询条件另一个查询语句查询出来的单个值

    例:select * from teacher_class where teacher_id = (select id from teacher1 where name='zhansan');[小结本条查询的语句是另外一条查询的结果]

      

      2.列子查询

      概念:本条查询语句的查询条件 是 另一个查询语句查询出来的一列结果

    select * from teacher_class where teacher_id in (select id from teacher1 where name='孔子' or numb='n10078');[小结本条查询是另外一条查询结果的一个集合]

      3.行子查询

      概念:本条查询语句中的查询条件 是 另一个查询语句所查出来的一行记录

    select * from stu2 where (teacher_name,teacher_numb) = (select name,numb from teacher1 where id=4);

      4.exists子查询

      概述:TIPS:exists子查询和查询的具体数据没有关系,只和是否查询的出数据有关。

      

    select * from stus where exists (select name from teacher1 where stu2.teacher_name=teacher1.name);

    (三)连接查询

      1.内连接(inner join)

       概念:内连接就是左右两个表连接时候两边都相同的时候会显示查询结果否则不显示(关键字 [inner] join)

    select * from stu3 [inner] join class2 on stu3.class_name = class2.name; [where可以替换on,使用using必须字段相同]

      2.左外连接(left [outer] join)

      概念:左连接就是以左表为主表连接右表如果右表不存在则显示为NULL

    select * from stu3 left [outer] join class2 on stu3.class_name = class2.name; [只能用on、using]

      3.右外连接(right [outer] join)

      概念:右连接就是以右表为主表连接左表如果左表不存在则显示为NULL

    select * from stu3 right[outer] join class2 on stu3.class_name = class2.name; [只能用on、using]

      4.全外连接是通过union和union all 实现的(此处省略)

      5.自然连接其实就是内连接使用using的条件因此可以根据自己条件掌握前面就够用

     

    IT这条路,当你懂得越多的时候,那么你不懂的也就会越多了.
  • 相关阅读:
    linux学习-----项目上线步骤
    linux学习-----数据库MySQL
    linux学习-----shell基础
    linux学习-----网络基础,网络相关命令,项目上线流程
    linux学习-----linux权限,sudo的使用
    linux学习-----开机启动项设置,ntp服务,防火墙服务,rpm服务,cron服务
    linux学习-----用户,用户组管理 网络设置 ssh服务
    linux学习-----vim编辑器的使用
    linux学习-----指令学习2 及练习
    linux学习-----指令学习1
  • 原文地址:https://www.cnblogs.com/learningPHP-students2018/p/10117836.html
Copyright © 2011-2022 走看看