我有一个新闻表,每个记录都有字段:
news_id (INT), parent_id (INT) , subitems (INT)
我希望每条记录都包含其直接子女的总数(计数)
e.g。 (我希望结果像那样)
news_id: 1, parent_id: 0, subitems: 2
news_id: 2, parent_id: 1 , subitems: 0
news_id: 3, parent_id: 1 , subitems: 0
我如何正确地做这样的事情:
UPDATE news n
SET subitems = (SELECT COUNT(*) FROM `news` AS `n2`
WHERE `n2`.`parent_id` = `n`.`news_id`)
如上所示,出现以下错误:
#1093 - You can't specify target table 'n' for update in FROM clause
答案 0 :(得分:0)
这就是我解决它的方法:
注意:这只是性能上的,只需执行一次,但不能进行持续操作
UPDATE news n
SET subitems = (SELECT COUNT(*)
FROM (SELECT parent_id FROM `news` AS `n2`
WHERE `n2`.`parent_id` <> '0') AS n3 WHERE n3.parent_id = n.news_id)
WHERE n.parent_id = '0'