2016-11-28 140 views
0

我試圖寫一個簡單的查詢,但輸出是不正確的:簡單的SQL查詢與多個表

Herer我的代碼:

SELECT oc_order_product.order_id AS ordernumber, oc_order_product.quantity, 
     oc_order_product.model, oc_order_product.name, 
     oc_order.shipping_company, oc_order.shipping_firstname, 
     oc_order.shipping_lastname, oc_order.shipping_city, oc_product.location 
FROM oc_order_product, 
    oc_order, 
    oc_product 
WHERE oc_order.order_id = oc_order_product.order_id 
    AND oc_order.order_status_id = 1 
    AND oc_product.location = 1 
ORDER BY ordernumber, oc_order_product.model 

輸出是與所有產品的列表oc_order.order_status_id = 1,但第二個AND(oc_product.location = 1)未應用。哪裏不對?我不使用JOIN,因爲我不太瞭解它。

+3

今天提示:切換到現代,明確的'JOIN'語法!易於編寫(沒有錯誤),更易於閱讀(和維護),並且在需要時更容易轉換爲外部聯接。 – jarlh

+1

請開始使用現代連接語法http://www.w3schools.com/sql/sql_join.asp –

+0

您需要一個更多的連接條件,在oc_product上。 – jarlh

回答

0

現在用現代的,明確的JOIN

SELECT oc_order_product.order_id AS ordernumber, oc_order_product.quantity, 
     oc_order_product.model, oc_order_product.name, 
     oc_order.shipping_company, oc_order.shipping_firstname, 
     oc_order.shipping_lastname, oc_order.shipping_city, oc_product.location 
FROM oc_order_product 
    INNER JOIN oc_order ON oc_order.order_id = oc_order_product.order_id 
    INNER JOIN oc_product ON oc_product.id = oc_order_product.product_id 
WHERE oc_order.order_status_id = 1 
    AND oc_product.location = 1 
ORDER BY ordernumber, oc_order_product.model 

,去年加入

INNER JOIN oc_product ON oc_product.id = oc_order_product.product_id 

只是一個猜測,因爲我不知道該用哪些列!

0

jarlh正在猜測oc_product.id = oc_order_product.product_id

我要去猜測,你的數據元素名稱始終如一和獨特的整個架構命名,因此建議您使用超現代NATURAL JOIN

SELECT order_id AS ordernumber, quantity, 
     model, name, shipping_company, shipping_firstname, 
     shipping_lastname, shipping_city, location 
    FROM oc_order_product 
     NATURAL JOIN oc_order 
     NATURAL JOIN oc_product 
    WHERE order_status_id = 1 
     AND location = 1 
    ORDER 
     BY ordernumber, model; 

...不就行了投注農場,雖然。