无法更新并在mysql中的单个查询中选择

时间:2019-02-11 11:59:56

标签: mysql laravel

UPDATE sub_categories 
   set creatives_count = 
            ( SELECT COUNT(services.sub_category_id) 
                from sub_categories 
                left 
                join services 
                  on (sub_categories.id = services.sub_category_id) 
               GROUP 
                  BY sub_categories.id);
  

BlockquoteError:表'sub_categories'被指定两次,既作为'UPDATE'的目标,又作为数据的单独来源。

如何使用在子查询中获得的结果来更新列。

2 个答案:

答案 0 :(得分:0)

您可以在下面尝试-

UPDATE  sub_categories s 
join
(
  SELECT COUNT(services.sub_category_id) as cnt from sub_categories 
  left join services on sub_categories.id = services.sub_category_id
  GROUP BY sub_categories.id
)A on s.id=A.id
set creatives_count = a.cnt

答案 1 :(得分:0)

您可以在子查询上使用内部联接

UPDATE sub_categories 
INNER JOIN (
     SELECT sub_categories.id my_id, COUNT(services.sub_category_id)  my_count
     FROM sub_categories 
     LEFT JOIN services ON sub_categories.id = services.sub_category_id
     GROUP BY sub_categories.id) t ON t.my_id =  sub_categories.id 
SET creatives_count =  t.my_count