Thanks to Mari's answer I found a solution to my similar problem. But I wanted to add a bit of an explanation which for me at first wasn't too clear from his answer.
What I wanted to do would have been as simple as the following:
UPDATE my_comments AS c
SET c.comment_responses = (
SELECT COUNT(c1.*) FROM my_comments AS c1
WHERE c.uid = c.parent_uid
);
Thanks to Mari I then found the solution on how to achieve this without running into the error You can't specify target table 'p1' for update in FROM clause
:
UPDATE my_comments AS c
INNER JOIN (
SELECT c1.parent_uid, COUNT(*) AS cnt
FROM my_comments AS c1
WHERE c1.parent_uid <> 0
GROUP BY c1.parent_uid
) AS c2
SET c.comment_responses = c2.cnt
WHERE c2.parent_uid = c.uid;
My problems before getting to this solution were 2:
- the
parent_uid
field doesn't always contain an id of a parent which is why I added the WHERE
statement in the inner join
- I didn't quite understand why I would need the
GROUP BY
until I executed the SELECT
statement on it's own and the answer is: because COUNT
groups the result and really counts everything. In order to prevent this behavior the GROUP BY
is needed. In my case I didn't have to group it by uid
though but the parent_uid
to get the correct count. If I grouped it by uid
the COUNT
would always be 1 but the parent_uid
existed multiple times in the result. I suggest you check the SELECT
statement on it's own to check if it's the result you expect before you execute the full UPDATE
statement.