简体   繁体   中英

MySQL UPDATE using target table

I'm trying to update all totals in a table based on values from the same table.

UPDATE posts AS p SET posts.answers_total = (
    SELECT COUNT(posts.id)
    FROM posts
    WHERE posts.post_id = p.id
)

I get the following error:

Error Code: 1093
You can't specify target table 'p' for update in FROM clause

Seems to be a common issue but I can't quite piece together a query that will perform this. I've seen many examples with INNER JOIN and additional sub queries but they all assume we know the id or some other value.

If I wrap this with more queries than the original p table get's lost. Is there anyway to make this query update on the whole table without knowing any id or other values?

Not to worried about performance at the moment just need something relatively simple working.

You can rewrite your update query using a JOIN:

UPDATE
  posts INNER JOIN (
    SELECT id, COUNT(*) cnt
    FROM posts
    GROUP BY id
  ) p ON posts.post_id = p.id
SET
  posts.answers_total = p.cnt

Ok, I finally got the correct query based on the answer from @fthiella and comment from @gordon-linoff.

There are a few important changes though:

  1. It should be on posts.id = p.post_id , not the other way around
  2. Should be a LEFT JOIN to account for 0 values.
  3. Need an IFNULL(p.cnt, 0) to avoid warnings and fill in a default value.

Works like a charm, although I'm not sure about performance.

UPDATE posts
LEFT JOIN (
    SELECT post_id, COUNT(*) cnt
    FROM posts
    WHERE STATUS = 'active' AND post_id <> 0
    GROUP BY post_id
) p ON posts.id = p.post_id
SET posts.answers_total = IFNULL(p.cnt, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM