0%

关于join查询

SQL执行顺序

我们知道,手写sql语句大概是如下步骤:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
SELECT 
<select_list>
FROM
<left_table><join_type>
JOIN <right_table> ON<right_condition>
WHERE
<where_condition>
GROUP BY
<group_by_list>
HAVING
<having_condition>
ORDER BY
<order_by_condition>
LIMIT <limit_number>

随着Mysql版本的更新换代,其优化器也在不断的升级,优化器会分析不同执行顺序产生的性能消耗不同而动态调整执行顺序。比如,经常出现的查询顺序:

1
2
3
4
5
6
7
8
9
10
11
FROM <left_table>
ON <join_condition>
<join_type> JOIN <right_table>
WHERE<where_condition>
GROUP BY <group_by_list>
HAVING <having_condition>
SELECT
<select_list>
ORDER BY
<order_by_condition>
LIMIT <limit_number>

join图

image.png

共有与独有
共有:满足 a.deptid = b.id 的叫共有
A独有: A 表中所有不满足 a.deptid = b.id 连接关系的数据

七个join

根据共有和独有,可以知道有七中join关系:

  1. A、B两表共有
    select * from t_emp a inner join t_dept b on a.deptId = b.id;

  2. A、B两表共有+A的独有
    select * from t_emp a left join t_dept b on a.deptId = b.id;

  3. A、B两表共有+B的独有
    select * from t_emp a right join t_dept b on a.deptId = b.id;

  4. A的独有
    select * from t_emp a left join t_dept b on a.deptId = b.id where b.id is null;

  5. B的独有
    select * from t_emp a right join t_dept b on a.deptId = b.id where a.deptId is null;

  6. AB全有
    #MySQL Full Join的实现 因为MySQL不支持FULL JOIN,下面是替代方法
    #替代方法: left join + union(可去除重复数据)+ right join
    SELECT * FROM t_emp A LEFT JOIN t_dept B ON A.deptId = B.id
    UNION
    SELECT * FROM t_emp A RIGHT JOIN t_dept B ON A.deptId = B.id

    这里因为要联合的缘故,不能考虑到小表驱动大表的情况。只能用right join。要保证查询出来的数字要一致。

  7. A的独有+B的独有

    FROM t_emp A LEFT JOIN t_dept B ON A.deptId = B.id WHERE B.id IS NULL
    UNION
    SELECT * FROM t_emp A RIGHT JOIN t_dept B ON A.deptId = B.id WHERE A.deptId IS NULL;

子查询与join查询的理解

子查询理解:①先知道需要查询并将数据拿出来(若from 后的表也是一个子查询结果)。②在去寻找满足判断条件的数据(where,on,having 后的参数等)。而这些查询条件通常是通过子查询获得的。

join理解:执行完第一步后的结果为一张新表。在将新表与 t_emp 进行下一步的 left join 关联。
先推出如何获得条件,再像算数题一样一步一步往下 join。可以交换顺序,但只能是因为条件间不相互关联时才能交换顺序。

join 能用到索引,但是子查询出来的表会使索引失效。

-------------本文结束感谢您的阅读-------------
谢谢你请我吃糖果