1、什么使用使用
例如:现在需要统计超市每个商品每月卖了多少
商品表(商品编号,商品名称)
销售表(商品编号,销售数量,月份)
select a.商品名称, sum(b.销售数量), b.月份
from 商品表 a, 销售表 b
where a.商品编号 = b.商品编号
group by b.月份, b.商品编号
上面没有统计到未卖出去的商品。
这种情况就需要使用到左连接或右连接。
select a.商品名称, isnull(sum(b.销售数量), 0), b.月份
from 商品表 a Left Join 销售表 b
on a.商品编号 = b.商品编号
group by b.月份, b.商品编号
注:未卖出去的商品为null
2、连接的分类
内连接:典型的连接运算
外连接:在FROM子句中外连接可以是左向外连接、右向外连接或完整外部连接
LEFT JOIN 或 LEFT OUTER JOIN
将返回左表的所有行。如果左表的某行在右表中没有匹配行,则将为右表返回空值。
RIGHT JOIN 或 RIGHT OUTER JOIN
将返回右表的所有行。如果右表的某行在左表中没有匹配行,则将为左表返回空值。
交叉连接:交叉连接返回左表中的所有行,左表中的每一行与右表中的所有行组合。交叉连接也称作笛卡尔积。
例子:
a表 b表
id 姓名 id 年龄 parent_id
1 张三 1 18 1
2 李四 2 22 2
3 王二 3 20 4
a.id和b.parent_id存在关系
1)内连接
select a.*, b.* from a inner join b on a.id = b.parent_id
结果:
id 姓名 id_1 年龄 parent_id
1 张三 1 18 1
2 李四 2 22 2
2)左连接
select a.*, b.* from a left join b on a.id = b.parent_id
结果:
id 姓名 id_1 年龄 parent_id
1 张三 1 18 1
2 李四 2 22 2
3 王二 null null null
3)右连接
select a.*,b.* from a right join b on a.id=b.parent_id
结果:
id 姓名 id_1 年龄 parent_id
1 张三 1 18 1
2 李四 2 22 2
null null 3 20 4
4)完全连接
select a.*,b.* from a full join b on a.id=b.parent_id
结果:
id 姓名 id_1 年龄 parent_id
1 张三 1 18 1
2 李四 2 22 2
3 王二 null null null
null null 3 20 4