0

join 的笛卡尔积

 3 years ago
source link: https://mednoter.com/sql-join.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

join 的笛卡尔积

这周在统计数据时,误用了left join,我觉得有必要总结一下。

问题的场景是这样的:一条product可能对应多个订单,我想通过left join把右侧的重复订单记录过滤掉,1个商品只显示1个订单信息。但查询结果却和我的预期很不一致。

主表id=1的商品出现两条查询结果。


select products.id, products.product, orders.id, orders.price, orders.product_id
from products
left join orders
on products.id = orders.product_id

products 表

id product 1 剃须刀 2 皮鞋 3 旅行箱

orders 表

id price product_id 1 180 1 2 200 1 3 200 5 products.id products.product orders.id orders.price orders.product_id 1 剃须刀 1 180 1 1 剃须刀 2 200 1 2 皮鞋       3 旅行箱      
  1. n:n 时,查询结果的数量等于笛卡尔积
  2. 条件不符时,left(or right) join 决定从哪张表中拿数据,并不能过滤1:n的关系。
吕小荣
04 November 2013

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK