sql多表查询的总结

多表查询介绍

含义:当查询的字段来自于多个表时,就会用到多表查询(也叫连接查询)
笛卡儿乘积现象:表1,有m行,表2有n行,结果=m*n行
发生的原因:没有有效的连接条件

按功能分类:
      内连接:等值连接 非等值连接 自连接
      外连接:左外连接 右外连接 全外连接
      交叉连接

多表查询具体分析

  1. 等值连接
//查询美女和对应的男友名
select name,boyname from boys,beauty where beauty.boyfriend_id=boys.id;
  • 为表起别名好处:
    • 提高语句的简洁度
    • 区分重名字段
//查询员工名、工种号、工种名
select last_name,e.job_id,j.job_title from 
employees e ,jobs j where e.job_id=j.job_id

  • 加筛选条件
//查询有奖金的员工名,部门名
select last_name,department_name from employees e,department d where e.department_id =d.department_id and e.commission_pct is not null;

//查询城市名中第二个字符为o的部门名和城市名
select department_name,city from department d,location l where d.location_id =l.location_id and city like '_o%';

// 查询每个城市的部门个数
select count(*) 个数,city from departments d,locations l where d.location_id=l.location_id group by city;

猜你喜欢

转载自blog.csdn.net/hj1997a/article/details/82787581