Mysql自联结深入剖析

前言:在学习Mysql时遇到自联结实,在我把书上给的自联结例子修修改改之后,出现了意想不到的结果,对我这个门外汉来说真是个大麻烦

Mysql自联结

  • 自联结通常作为外部语句用来代替从相同表中检索数据时使用的子查询语句

自联结

SELECT * FROM products AS p1, products AS p2;

这里写图片描述

返回数据结果为196行,由此可以看出他是 p1 和 p2 的笛卡尔积; 可以推测,所谓的自联结就是把同一张表,看成独立的,不同的两张表p1,p2

SELECT * FROM products AS p1, products AS p2 WHERE p1.vend_id = p2.vend_id;

这条sql作用很明显就是筛选出来上图中p1.vend_id = p2.vend_id的数据集

SELECT * FROM products AS p1, products AS p2 WHERE p1.vend_id = p2.vend_id AND p2.prod_id = "DTNTR";

这条sql作用很明显就是筛选出来上条sql结果级中p2.prod_id = “DTNTR”的数据集(p2为驱动表,p1为数据表);为什么要这么做呢,请大家认证思考笛卡尔积的运算过程和结果。。。

笛卡尔积运算前后向以及数据集显示结果的顺序

SELECT p1.prod_id AS prod1_id, p2.prod_id AS prod2_id FROM products AS p2, products AS p1;
SELECT p2.prod_id AS prod2_id, p1.prod_id AS prod1_id FROM products AS p2, products AS p1;

SELECT p1.prod_id AS prod1_id, p2.prod_id AS prod2_id FROM products AS p1, products AS p2;
SELECT p2.prod_id AS prod2_id, p1.prod_id AS prod1_id FROM products AS p1, products AS p2;

/* 
运行以上4条sql,观察结果可知:

1、SELECT 子句决定数据集显示(列)的顺序
2、FROM 子句决定笛卡尔积运算的前项,后者为前项(两张独立表的情况下)
*/

注:《Mysql 必知必会》p108,所用的数据表为书上提供的原数据表

参考博客:

红黑联盟:MySQL学习足迹记录14–表别名和自联结

结束语:深夜写博客有点仓促,望读者见谅;欢迎批评指正

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页