SQL语法错误 - 连接两个表时更新

时间:2015-01-06 02:13:06

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

有没有人可以帮我理解为什么我在尝试运行此查询时出现语法错误?

UPDATE exp_store_orders
SET exp_store_orders.order_status_name = "Digital"
    JOIN exp_store_order_items
        ON exp_store_orders.id = exp_store_order_items.order_id
    JOIN exp_channel_data
        ON exp_store_order_items.entry_id = exp_channel_data.entry_id
GROUP BY exp_store_order_items.order_id
HAVING COUNT(CASE exp_channel_data.field_id_50 WHEN '' THEN null ELSE 1 END) =     COUNT(exp_store_order_items.order_id)

这会显示我想要更新的订单的ID,但出于某种原因,上述操作会引发语法错误。

SELECT exp_store_orders.id
FROM exp_store_orders
    JOIN exp_store_order_items
        ON exp_store_orders.id = exp_store_order_items.order_id
    JOIN exp_channel_data
        ON exp_store_order_items.entry_id = exp_channel_data.entry_id
GROUP BY exp_store_order_items.order_id
HAVING COUNT(CASE exp_channel_data.field_id_50 WHEN '' THEN null ELSE 1 END) =     COUNT(exp_store_order_items.order_id)

感谢任何帮助,谢谢!

2 个答案:

答案 0 :(得分:1)

MySQL update join的正确语法是join 之前 set。此外,group by中不允许update

相反,从子查询中获取列表并使用另一个join来设置行。子查询实际上不需要exp_store_orders,因此可以删除:

UPDATE exp_store_orders o JOIN
       (SELECT oi.order_id
        FROM exp_store_order_items oi JOIN
             exp_channel_data cd
             ON oi.entry_id = cd.entry_id
        GROUP BY oi.order_id
        HAVING COUNT(CASE cd.field_id_50 WHEN '' THEN null ELSE 1 END) = COUNT(oi.order_id)
       ) ou
       on o.id = ou.order_id
    SET o.order_status_name = 'Digital';

答案 1 :(得分:0)

您在语句中缺少WHERE子句。

UPDATE [LOW_PRIORITY] [IGNORE] table_reference
    SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
    [WHERE where_condition]
    [ORDER BY ...]
    [LIMIT row_count]