I have a few groups of data. Each group has a some property field.
For example:
_________________________
| id | value | property |
--------------------------
| 1 | 2 | 3 |
--------------------------
| 2 | 2 | 3 |
--------------------------
| 3 | 2 | 3 |
--------------------------
| 4 | 2 | 4 |
-------------------------
| 5 | 2 | 4 |
--------------------------
| 6 | 2 | 4 |
--------------------------
How can I update two strings ordered by id ASC with property = 3, and 2 strings ordered by id ASC with property = 4 by one query?
I want to update 2 of 3 rows with property = 3 and update 2 of 3 rows with property = 4. For example: rows with id 1 and 2, and rows with id 4 and 5
i.e. i want update groups of data with different conditions by one query
Here’s the solution, and see discussion following:
To illustrate, and assuming your table is called
t, and the initial state is:The result of running this query is:
A brief explanation of the query:
I pick up the first two
ids for each property using theSUBSTRING_INDEX(GROUP_CONCAT(id order by id), ',', 2)statement.I combine the above using
GROUP_CONCAT(ids) as matching_idsto get all validids.Finally, I update all rows in the table where the
idis within combinedmatching_idstext.Notes:
You should verify your
group_concat_max_lenvariable is long enough. Default is 1024. You most probably want to have this in the millions, anyhow (regardless of my answer).The query is far from being optimal. It answers your question, but you can’t have an optimal query here.
You are most probably better off with a transaction containing two or three queries.
Good luck!