I’ve stumbled on a problem which is supposedly should have a valid solution in a single MySQL query, yet I can’t figure it out (I’m far from an expert in MySQL, alas).
The table has the following columns: A, B, C. (A, B) is a primary key (INTs). C – is a string. The table is populated with records.
Under some conditions I need to update a value x in column A to new value y. If some records do already have y in A (can be many at once, for records with different values in B), “duplicate key(s)” condition occurs. In such case, I need to concatenate values in C from old records and corresponding pending updates, for every specific b.
Example:
| A | B | C | 1 | 2 | ABC | 1 | 4 | DEF | 2 | 2 | GHI | 2 | 4 | JKL | 2 | 5 | MNO
After update in A as 2 -> 1, I need to get:
| A | B | C | 1 | 2 | ABCGHI | 1 | 4 | DEFJKL | 1 | 5 | MNO
There is a well-known INSERT ... ON DUPLICATE KEY UPDATE statement. But how to handle gracefully the same problem on updates? I’m not sure if and how REPLACE statement or REPLACE function can be used for the task.
Thanks in advance.
I think, whatever happens, you will need two statements:
See it on sqlfiddle.
If there is a risk of concurrency issues, you will obviously need to perform these within a transaction to preserve atomicity.