This question already has answers here:
MySQL Error 1093 - Can't specify target table for update in FROM clause
                                
                                    (15个答案)
                                
                        
                                2年前关闭。
            
                    

测试1:

更新tb_chapters t set t.order_id =(SELECT COUNT(*)AS c从tb_chapters t2 WHERE t.bid = t2.bid AND t.id> t2.id)


错误:
1093 - You can't specify target table 't' for update in FROM clause




测试2:

更新tb_chapters t set t.order_id =(选择t2.c FROM(选择COUNT(t1.id)AS c从tb_chapters t1到t1.bid = t.bid AND t1.id

错误:
1054 - Unknown column 't.bid' in 'where clause'




测试3:

更新tb_chapters AS t联接(SELECT id,COUNT(id)AS c从tb_chapters t1那里t1.bid = t.bid AND t1.id

错误:
1054 - Unknown column 't.bid' in 'where clause'

最佳答案

您可以先在derived table中获取bid和相应的预期Count值。和,
现在,Join再次使用基表派生表,并基于两个表使用Update
请注意,我已将您的JOIN更改为LEFT JOIN,这样在没有其他id的情况下,它将更新为0,小于特定idbid
使用Ifnull()函数,我们可以检查一个值是否为Null并将其设置为另一个值(在这种情况下,将上一点讨论的出价设置为0)。


请尝试以下操作:

UPDATE tb_chapters AS t3
JOIN
(
SELECT t1.bid, IFNULL(COUNT(t2.id), 0) AS c
FROM tb_chapters AS t1
LEFT JOIN tb_chapters AS t2 ON t2.bid = t1.bid
                                AND t2.id < t1.id
GROUP BY t1.bid
) AS t4 ON t4.bid = t3.bid

SET t3.order_id = t4.c

关于mysql - MySQL如何更新同一表中的字段值? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52453623/

10-11 00:34