• mysql学习-mysql多表查询


    1、简介

      同时从多张表查询数据,一般来说多张表之间都会存在某种关系

    2、基本用法

    2.1 语法

      select 列名1 别名1,列名2 别名2...

      from 表名1,表名2....

      where 条件

      order by 排序列1 asc|desc,排序列2 asc|desc...;

      

      通过将两张表的关联字段进行对比,去掉笛卡尔积,多表查询时一般都会存在某种关系

      select * from emp,dept where emp.deptno = dept.deptno;

    2.2 示例

      查询雇员编号、雇员姓名、工资、所在部门名称和位置 (考虑查询的数据在几个表里有)

      select empno,ename,sal,dname,loc from emp e,dept d where e.deptno=d.deptno;

      查询雇员姓名,工资,入职时间,所在部门编号,部门名称

      select ename,sal,hiredate,d.deptno,dname from emp e,dept d where e.deptno = d.deptno;---多表查询时,如果多表中出现同名的列,当查询是需要指定前缀 d.deptno

      查询雇员姓名、雇员工资、领导姓名、领导工资(自身连接)

        思路:因为领导的工资和姓名和员工的工资和姓名都存在同一个表里 emp表。 可以拿员工的领导编号去查询领导编号

      select a.ename 雇员姓名,a.sal 雇员工资,b.ename 领导姓名,b.sal 领导工资 from emp a,emp b where a.mgr = b.empno;

      查询雇员员工、雇员工资、部门名称、领导姓名、领导工资

      select a.ename a.sal b.name b.sal c.dname

      from emp a,emp b,dept  c

      where a.mgr = b.empno and a.deptno = c.deptno;

      查询雇员姓名、雇员工资、部门名称、工资所在等级  (非等值连接)

      select e.ename 雇员姓名,e.sal 雇员工资,d.dname 部门名称, s. grade 工资等级

      from emp e,dept d ,salgrade s

      where e.deptno = d.deptno and e.sal between s.losal and s.hisal;

      

      查询雇员姓名、雇员工资、部门名称、雇员工资等级、领导姓名、领导工资、领导工资等级

      select e.ename 雇员姓名,e.sal 雇员工资,d.dname 部门名称,s,grade 雇员工资等级 ,m.ename 领导名称 ,m.sal 领导工资,sm.grade 领导工资等级

      from emp e,dept d,salgrade s,emp m,salgrade sm

      where e.depeno = d.deptno and e.sal between s.losal and s.hisal and e.mgr = m.empno and e.sal between sm.losal and sm.hisal;

  • 相关阅读:
    Redis集群的三种模式
    导航
    关于Django数据库mysql连接错误问题Connection to api@localhost failed. [08001] Could not create connection to d
    原码 反码 补码(宁宝宝)
    CSS实现限制显示的字数,超出显示
    flask源码系列
    django入门
    包的用法
    小技巧分享持续更新
    drf源码系列
  • 原文地址:https://www.cnblogs.com/jiliangceshi/p/12858895.html
Copyright © 2020-2023  润新知