2017-03-29 28 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