2

我收到以下错误:

#1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取在 'JOIN product_catalog ON product_catalog.entity_id 附近使用的正确语法

作为以下查询的结果:

SELECT sales_order.created_at , order_item.order_id, sales_order.increment_id, SUM(order_item.qty_ordered) AS qty_ordered , COUNT( * ) 

FROM order_item

JOIN sales_order
ON sales_order.entity_id = order_item.order_id
WHERE sales_order.created_at > '2012-11-15 00:00:00'

JOIN product_catalog
ON product_catalog.entity_id = order_item.product_id
WHERE product_catalog.size = 14

GROUP BY order_item.order_id;

过去,此查询的变体可用于按销售订单对不同类型的产品进行分组,而我只需要执行一个JOIN即可获得所需的所有信息。我遇到的问题来自第二个JOIN. 显然我错过了一些东西,但我真的不确定是什么。:(

4

3 回答 3

3

请确保WHERE条件必须是JOIN

SELECT sales_order.created_at , order_item.order_id, sales_order.increment_id, SUM(order_item.qty_ordered) AS qty_ordered , COUNT( * ) 

FROM order_item

JOIN sales_order
ON sales_order.entity_id = order_item.order_id

JOIN product_catalog
ON product_catalog.entity_id = order_item.product_id

WHERE product_catalog.size = 14
AND sales_order.created_at > '2012-11-15 00:00:00'
GROUP BY order_item.order_id;

首先,你必须拥有JOIN你需要的桌子。然后在WHERE子句之后出现条件。

于 2013-09-12T17:38:35.053 回答
3

JOIN...ON...子句它也是输入条件的部分,因此您不需要where子句,只需添加即可AND

SELECT sales_order.created_at , order_item.order_id, sales_order.increment_id, 
       SUM(order_item.qty_ordered) AS qty_ordered , COUNT( * )     
FROM order_item    
JOIN sales_order ON sales_order.entity_id = order_item.order_id
                 and sales_order.created_at > '2012-11-15 00:00:00'
JOIN product_catalog ON product_catalog.entity_id = order_item.product_id
                     and product_catalog.size = 14
GROUP BY order_item.order_id;

请考虑下面的示例,我添加了别名。使用它是一个好习惯,因为代码更具可读性。

SELECT SO.created_at , OI.order_id, SO.increment_id, 
       SUM(OI.qty_ordered) AS qty_ordered , COUNT( * )     
FROM order_item  OI  
JOIN sales_order SO ON SO.entity_id = OI.order_id
                 and SO.created_at > '2012-11-15 00:00:00'
JOIN product_catalog PC ON PC.entity_id = OI.product_id
                     and PS.size = 14
GROUP BY OI.order_id;
于 2013-09-12T17:43:18.770 回答
3

你的WHERE条款在错误的地方。请参阅下面的代码以了解正确的JOIN语法。

SELECT sales_order.created_at, 
    order_item.order_id, 
    sales_order.increment_id, 
    SUM(order_item.qty_ordered) AS qty_ordered, 
    COUNT( * )
FROM order_item
JOIN sales_order
    ON sales_order.entity_id = order_item.order_id
    AND sales_order.created_at > '2012-11-15 00:00:00'
JOIN product_catalog
    ON product_catalog.entity_id = order_item.product_id
    AND product_catalog.size = 14
GROUP BY order_item.order_id
于 2013-09-12T17:43:57.747 回答