2017-03-29 60 views
-5

我试图显示来自'Tucson'的客户购买的产品的平均价格,但是,即使有两个客户已经从Tuscon下订单,该查询返回null错误1064 - 在声明中

select AVG(product_price) from product where product_id in 
(select product_id from orderline where order_id in 
(select order_id from ordertable where cust_id in 
(Select cust_id from customer where city = 'Tuscon'))) 
+1

您会注意到,'fom'不是'from'。投票结束。 – bernie

+1

更新的问题(关于在查询中获取空值)听起来像是数据问题。没有看到数据,任何人都很难提供帮助。查询本身现在看起来是正确的。 –

回答

0

fom没有一个公认的关键字。 MySQL解析器不知道该怎么做,所以会抛出一个关于“无效语法”的错误。


考虑使用连接操作代替嵌套的IN子查询。如果我们保证:

  • 的product_id是在产品表中是唯一
  • ORDER_ID是ordertable表独特
  • CUST_ID是在客户表中是唯一

那么我们可以得到同样的结果集,已订购不同产品的平均价格...

SELECT AVG(p.product_price) 
    FROM (SELECT l.product_id 
      FROM orderline l 
      JOIN ordertable o 
      ON o.order_id = l.order_id 
      JOIN customer c 
      ON c.cust_id = o.cust_id 
      WHERE c.city = 'Tuscon' 
      GROUP BY l.product_id 
     ) q 
    JOIN product p 
    ON p.product_id = l.product_id 

如果我们想要t订购的所有产品帽子“均价”(不同的结果,平均考虑到时代的产物奉命数......然后我们可以使用这样的查询:

SELECT AVG(p.product_price) 
    FROM product p 
    JOIN orderline l 
    ON l.product_id = p.product_id 
    JOIN ordertable o 
    ON o.order_id = l.order_id 
    JOIN customer c 
    ON c.cust_id = o.cust_id 
WHERE c.city = 'Tuscon' 
0

你在查询中使用fom代替fromselect order_id fom ordertable where cust_id in

这应该是select order_id from ordertable where cust_id in