带有三个表的SQL更新

时间:2015-08-31 13:29:01

标签: mysql sql

我想在一个表格(A)的列中设置所有项目的值,这与另一个表格(C)中给出的条件相关。为了解决这个问题,我提到要使用这个查询:

Update Table1 AS A
SET A.Value = '1'
FROM Table1 AS A
INNER JOIN Table2 AS B
ON A.item = B.item
INNER JOIN Table3 AS C
ON B.item = C.item
WHERE C.Value = '2'

可悲的是,到目前为止这还不行,所以,我的错误在哪里?

以下是原始代码:

Update wp_postmeta 
SET A.meta_value = '0.25'
FROM wp_postmeta AS A
INNER JOIN wp_woocommerce_order_itemmeta AS B
ON B.meta_id = A.meta_id 
INNER JOIN wp_woocommerce_order_item  AS C
ON C.order_item_id = B.order_item_id 
WHERE C.Value = '%250g%'

2 个答案:

答案 0 :(得分:5)

它可能是'作为A'在第一行就是问题所在。尝试

Update Table1 
SET Value = '1'
FROM Table1 AS A
INNER JOIN Table2 AS B
ON A.item = B.item
INNER JOIN Table3 AS C
ON B.item = C.item
WHERE C.Value = '2'

编辑:在您的具体代码中,我认为在SET之后是A.问题。尝试:

Update wp_postmeta 
SET meta_value = '0.25'
FROM wp_postmeta AS A
INNER JOIN wp_woocommerce_order_itemmeta AS B
ON B.meta_id = A.meta_id 
INNER JOIN wp_woocommerce_order_item  AS C
ON C.order_item_id = B.order_item_id 
WHERE C.Value = '%250g%'

说明:在'更新...设置'的背景下声明的一部分,缩写' A'对SQL服务器毫无意义。

编辑:或者你可以按照i486的建议在下面的评论中进行。

答案 1 :(得分:0)

您可以使用类似于select语句的样式编写查询。这是恕我直言,更容易阅读,只需交换2个单词即可快速解释。

以下是更新的结果:

UPDATE Table1 A
INNER JOIN Table2 B
  ON A.item = B.item
INNER JOIN Table3 C
  ON B.item = C.item
SET A.Value = '1'
WHERE C.Value = '2';

如果需要在同一语句中,此样式还允许您更新除A之外的其他表中的列。

如果您想运行解释计划,要查看连接是否正常工作,您只需执行此操作:

EXPLAIN SELECT * FROM Table1 A
INNER JOIN Table2 B
  ON A.item = B.item
INNER JOIN Table3 C
  ON B.item = C.item
-- SET A.Value = '1'
WHERE C.Value = '2';