三表查询数据不对,请教:t_order(订单表)
userId 用户ID
order_id 订单ID
order_bets 订单金额t_order_Product(订单产品关联表)
order_id 订单ID
Product_id 产品ID
product_shares 产品份数t_product(产品表)
product_id 产品ID
product_name 产品名称select nvl(sum(a.order_bets),0) from t_order a, t_order_Product b, t_product c
where a.order_id = b.order_id and b.order_id = c.order_id
and a.userId = xxx and c.product_name = 'name'统计出来的数据不正确,请大家帮忙,急
userId 用户ID
order_id 订单ID
order_bets 订单金额t_order_Product(订单产品关联表)
order_id 订单ID
Product_id 产品ID
product_shares 产品份数t_product(产品表)
product_id 产品ID
product_name 产品名称select nvl(sum(a.order_bets),0) from t_order a, t_order_Product b, t_product c
where a.order_id = b.order_id and b.order_id = c.order_id
and a.userId = xxx and c.product_name = 'name'统计出来的数据不正确,请大家帮忙,急
where a.order_id = b.order_id and b.order_id = c.order_id
and a.userId = xxx and c.product_name = 'name'
userId 用户ID
order_id 订单ID PK
order_bets 订单金额 t_order_Product(订单产品关联表)
order_prinduct_id PK
order_id 订单ID
Product_id 产品ID
product_shares 产品份数 t_product(产品表)
product_id 产品ID PK
product_name 产品名称 select nvl(sum(a.order_bets),0) from t_order a, t_order_Product b, t_product c
where a.order_id = b.order_id and b.order_id = c.order_id
and a.userId = xxx and c.product_name = 'name' 数据库只建了PK约束,所有建立FK约束
from t_order a, t_order_Product b, t_product c
where a.order_id = b.order_id
and b.Product_id = c.product_id -- 你这个关联应该改为这样。
and a.userId = xxx
and c.product_name = 'name'
where a.order_id = b.order_id and b.Product_id = c.product_id
and a.userId = xxx and c.product_name = 'name'
where a.order_id = b.order_id and b.product_id = c.product_id
and a.userId = xxx and c.product_name = 'name' 但这样统计的结果还是不对!!!!!
where a.order_id = b.order_id and b.order_id = c.order_id
and a.userId = xxx and c.product_name = 'name' 解释你这个SQL:
其实你要统计的是某个单品的花费。
在你的3个表中:
t_order(订单表)
userId 用户ID
order_id 订单ID PK
order_bets 订单金额 t_order_Product(订单产品关联表)
order_prinduct_id PK
order_id 订单ID
Product_id 产品ID
product_shares 产品份数 t_product(产品表)
product_id 产品ID PK
product_name 产品名称
只有t_order设计到了金额,但是这个金额是该定单的金额。
一张定单可能有很多个单品,所以你的理解SQL存在逻辑问题。
目前你提供的3个表无法进行单品统计。
where a.order_id = b.order_id and b.product_id = c.product_id
and a.userId = xxx and c.product_name = 'name' 我的这个查询产生一个笛卡尔乘积,没有得到正确的结果,我在想,是不是我的表关系不对所致,我的订单与关联表的关系是一对多的关联,例如一个8块的订单过来,应该关联产品8份,而系统中如果没有足够的8份,我得再产生一次订单,这样一来,我的中间表中就存在二条记录对应于产品表,我的产品与关联表也是一对多的关系,一个产品可能被多个订单所关联,还得请各位大大帮忙,感觉自已SQL学的不扎实!!!!
where a.order_id = b.order_id and b.product_id = c.product_id
and a.userId = xxx and c.product_name = 'name' 我的这个查询产生一个笛卡尔乘积,没有得到正确的结果,我在想,是不是我的表关系不对所致,我的订单与关联表的关系是一对多的关联,例如一个8块的订单过来,应该关联产品8份,而系统中如果没有足够的8份,我得再产生一次产品,这样一来,我的中间表中就存在二条记录对应于产品表,我的产品与关联表也是一对多的关系,一个产品可能被多个订单所关联。修正一下
这样也是不对的,因为虽然一张定单只有一个产品项,但是同一个产品他有可能分两次或多次存放进去的,所以会造成多条笛卡尔积,就算是只有一个产品ID,也要先distinct一下,再关联才有效。当然如果一张定单里有多个产品ID的话,就无论如何也不会有正确的结果,建议修改表结构。