简体   繁体   English

具有多个表的简单SQL查询

[英]Simple sql query with multiple tables

I'm trying to write a simple query but the output is not correct: 我正在尝试编写一个简单的查询,但输出不正确:

Herer my code: 我的代码在这里:

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

The output is a list of all products with the oc_order.order_status_id = 1 but the second AND (oc_product.location = 1) is not applied. 输出是oc_order.order_status_id = 1但未应用第二个AND(oc_product.location = 1)的所有产品的列表。 What is wrong? 怎么了? I don't work with JOIN because I don't understand it really good. 我不喜欢JOIN,因为我不太了解它。

Now using modern, explicit JOIN : 现在使用现代的,显式的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

That last join 最后加入

INNER JOIN oc_product ON oc_product.id = oc_order_product.product_id

is just a guess, since I don't know which columns to use! 只是一个猜测,因为我不知道要使用哪些列!

jarlh is guessing that oc_product.id = oc_order_product.product_id . jarlh猜测oc_product.id = oc_order_product.product_id

I'm going to guess that your data element names are consistently and uniquely named throughout your schema and therefore suggest you use ultra-modern NATURAL JOIN : 我猜想您的数据元素名称在整个模式中都是一致且唯一的,因此建议您使用超现代的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;

...not betting the farm on it, though. ...不过不要将农场押在上面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM