2
UPDATE
  `details_audit` a
SET
  a.count_changes_below_100 = (
    SELECT
      COUNT(*)
    FROM
      `details_audit`
    WHERE
      sort_id < 100
  );

This worked on a previous version of MySQL but not with version 8.0.43:

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

How can I solve this?

4
  • what are you trying to achieve from this query? are you going to update all rows with a single value..is that really what you want to do? Commented Aug 29 at 23:48
  • This was written in the 1990s, but yes, this particular sub section focuses on changes made in the table before a certain point. Commented Aug 30 at 0:16
  • 1
    What version of MySQL were you using that permitted this? I've been using MySQL since before it first supported subqueries, and I don't recall it ever supporting updates where the same table is also referenced in a subquery. Commented Aug 30 at 1:02
  • Originally using an older version of MariaDB, but the Aria indexes would become corrupt, so I changed it to MySql. Commented Aug 30 at 11:01

2 Answers 2

4

In MySQL 8, you must put the subquery in a derived table:

UPDATE details_audit a
JOIN ( SELECT COUNT(*) AS cnt FROM details_audit WHERE sort_id < 100 ) b
SET a.count_change_below_100 = b.cnt
Sign up to request clarification or add additional context in comments.

1 Comment

I'd put the subquery to CTE.
0

Based on the comment you have provided, this is what I could understand,

for each row, store the number of rows with sort_id < 100 and also sort_id < this row’s sort_id (i.e. how many changes happened before me, but only in the first 100 changes).

For that we could do something like this, rather than updating a column with the same value in every row.

UPDATE details_audit a
JOIN (
    SELECT da1.id,
           (
               SELECT COUNT(*)
               FROM details_audit da2
               WHERE da2.sort_id < 100
                 AND da2.sort_id < da1.sort_id
           ) AS cnt
    FROM details_audit da1
) x
  ON a.id = x.id
SET a.count_changes_below_100 = x.cnt;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.