简体   繁体   中英

MySQL update values of all rows following the row that matches a certain value

I have a table that lists revision information for content articles. The table is indexed by the revision_id which is an auto increment. Each revision has a flag that indicates whether the revision is published or not, and each revision has a timestamp.

I am adding a new column initial_publication and this needs to be set to the timestamp of the first revision that was published for each content_id . If there are no prior revisions that were published, then the value should remain NULL .

So before I do my update query the table looks like this:

| revision_id | content_id | published | timestamp  | initial_publication |
| ----------- | ---------- | --------- | ---------  | ------------------- |
| 1           | 1          | FALSE     | 1564621260 | NULL                |
| 2           | 1          | FALSE     | 1564621923 | NULL                |
| 3           | 2          | TRUE      | 1564625583 | NULL                |
| 4           | 2          | TRUE      | 1564627203 | NULL                |
| 5           | 1          | TRUE      | 1564630803 | NULL                |
| 6           | 3          | FALSE     | 1564630830 | NULL                |
| 7           | 3          | TRUE      | 1564631973 | NULL                |
| 8           | 3          | FALSE     | 1564632333 | NULL                |

After the update query it should look like this:

| revision_id | content_id | published | timestamp  | initial_publication |
| ----------- | ---------- | --------- | ---------  | ------------------- |
| 1           | 1          | FALSE     | 1564621260 | NULL                |
| 2           | 1          | FALSE     | 1564621923 | NULL                |
| 3           | 2          | TRUE      | 1564625583 | 1564625583          |
| 4           | 2          | TRUE      | 1564627203 | 1564625583          |
| 5           | 1          | TRUE      | 1564630803 | 1564630803          |
| 6           | 3          | FALSE     | 1564630830 | NULL                |
| 7           | 3          | TRUE      | 1564631973 | 1564631973          |
| 8           | 3          | FALSE     | 1564632333 | 1564631973          |

I am currently looping over all content items and executing a query for each individual content item, but this takes a lot of time since the table has hundreds of thousands of rows.

I figured it out:

UPDATE revisions r, (
  SELECT revision_id, content_id, timestamp
  FROM revisions
  WHERE published = TRUE
  GROUP BY content_id
  ORDER BY revision_id
) s
SET r.initial_publication = s.timestamp
WHERE r.content_id = s.content_id AND r.revision_id >= s.revision_id;

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