2016-11-28 138 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; 

...不就行了投注农场,虽然。