具有多个表的简单sql查询

时间:2016-11-28 15:00:41

标签: sql join multiple-columns

我正在尝试编写一个简单的查询,但输出不正确:

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合作,因为我不太了解它。

2 个答案:

答案 0 :(得分: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

只是猜测,因为我不知道要使用哪些列!

答案 1 :(得分: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;

......不要把农场押在它上面。