连接查询-笛卡尔积

多表查询,当查询字段来自多个表

笛卡尔积现象:表一有m行,表二有n行,结果=m*n行

发生:没有有效的连接条件

如何避免:赋予有效的连接条件

分类:

  年代分类:

  sq192标准 只支持内连接

  sq199标准【推荐】

  功能分类:

  内连接:

      等值连接

      非等值连接

      自连接

  外连接:

      左外连接

      右外连接

      全外连接

  交叉连接

#如何避免笛卡尔积

{ 

select  * from beauty ;

select * from boys ;

select name,boyname from boys,beauty

where beauty.boyfriend id = boys.id ;

}

#一、sq192标准

{

#1.等值连接

/*

多表等值连接的结果为多表交集部分

n表连接至少需要n-1个连接条件

多表的顺序没有要求

一般为表起别名

可以搭配前面介绍的所有子句,如排序、分组、筛选

*/

#案例一:查询男女生配对

select  * from beauty ;

select * from boys ;

select name,boyname from boys,beauty

where beauty.boyfriend id = boys.id ;

#案例二:查询员工名对应部门名

select last_name,department_name

from employees,departments

where employees.department_id = departments.department_id ;

#2.为表起别名

/*

提高语句的简洁度

区分多个重名的字段

注意:起了别名就不能用原来的表名去限定

*/

#查询员工名、工种号、工种名

select E.last_name , E.job_id , J.job_title

from employees as E , jobs as J

where E.job_id = J.job_id ;

#3.两个表的顺序是否可以交换:可以

#4.可以加筛选?

#查询有奖金的员工名、部门名

selecrt last_name,department_name

from employees e,departments 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%' ;

#5.可以加分组

#案例一、查询每个城市的部门个数

select count(*) 个数,city

from departments d,locations l

group by city ;

#案例二:查询有奖金的部门名的领导编号和该部门最低工资

select department_name,d.manger_id,min(salary)

from department d,employees e

where d.department_id = e.department_id

and commission_pct is not null

group by department_name,d.mannger_id ;

#6.可以加排序

#案例:查询每个工种的工种名和员工个数,并按员工个数降序

select job_title,count(*)

from employees e,jobs j

where e.job_id = j.job_id

group by job_title

order by count(*0) desc ;

#7.三表连接

#案例:查询员工名,部门名和所在的城市

select last_name,department_name,city

from employees e,departments d,locations l

where e.department_id = d.department_id

and d.location_id = l.location_id ;

 

#2.非等值连接

#案例一:查询员工的工资和工资级别

select salary,great_level

from employee e,job_generation g

where salary betwwen g.lowest_sal and g.highest_sal ;

#3.自连接 相当于等值连接,只不过只有自己一个表

案例:查询员工名和上级的名字

select e.employee_id,e.last_name,m.employee_id,m.last_name

from employees e,employees m

where e.employee_id = m.employee_id;

 

}

posted @   平凡的柳先生  阅读(96)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示