且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用WHERE子句和INNER JOIN的MySQL更新查询不起作用

更新时间:2023-10-23 14:10:58

查询应如下所示,您已加入同一张表,因此存在唯一别名的问题.我添加了表别名以提高可读性.

UPDATE 
sales_flat_order sfo
INNER JOIN sales_flat_order_grid sfog 
ON sfog.entity_id = sfo.entity_id      
SET sfo.coupon_code = "newcoupon"
WHERE sfog.increment_id = "12345678" ; 

Can't seem to reach the next step in my update query. I'm able to successfully view columns related to the select no problem:

SELECT sales_flat_order_grid.entity_id,sales_flat_order_grid.increment_id,sales_flat_order.coupon_code
FROM sales_flat_order_grid 
INNER JOIN sales_flat_order ON sales_flat_order_grid.entity_id = sales_flat_order.entity_id     
WHERE sales_flat_order_grid.increment_id = "12345678";

This shows 3 columns all where related to the correct increment_id.

The next step is to update the sales_flat_order.coupon_code field. Here is my attempt:

UPDATE sales_flat_order 
INNER JOIN sales_flat_order ON sales_flat_order_grid.entity_id = sales_flat_order.entity_id      
WHERE sales_flat_order_grid.increment_id = "12345678"
SET coupon_code = "newcoupon";

But I keep getting a Not unique table/alias: 'sales_flat_order' error message. Could someone point me in the right direction?

The query should be as below, you have joined the same table and hence the problem of unique alias. I have added table alias for better readability.

UPDATE 
sales_flat_order sfo
INNER JOIN sales_flat_order_grid sfog 
ON sfog.entity_id = sfo.entity_id      
SET sfo.coupon_code = "newcoupon"
WHERE sfog.increment_id = "12345678" ;