MySQL在第二个JOIN上抛出错误

时间:2013-09-12 17:37:43

标签: mysql sql join syntax-error inner-join

我收到以下错误:

#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。很明显我错过了什么,但我真的不确定是什么。 :(

3 个答案:

答案 0 :(得分: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条款到达条件之后。

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

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