Update column value for group of rows whose values are same

时间:2017-07-12 08:09:01

标签: php mysql

Want to update group(any unique str) for a combination of common values of company_id and city_id columns.

Table Data

    ----------------------------------------
    | id |   group  | company_id | city_id |
    ----------------------------------------
    | 1  |  (null)  |   1        |    12   |
    | 2  |  (null)  |   1        |    12   |
    | 3  |  (null)  |   1        |    13   |
    | 4  |  (null)  |   1        |    13   |
    | 5  |  (null)  |   2        |    12   |
    | 6  |  (null)  |   2        |    12   |
    | 7  |  (null)  |   3        |    14   |
    ----------------------------------------

Expected result

----------------------------------------
| id |   group  | company_id | city_id |
----------------------------------------
| 1  |   123    |   1        |    12   |
| 2  |   123    |   1        |    12   |
| 3  |   223    |   1        |    13   |
| 4  |   223    |   1        |    13   |
| 5  |   345    |   2        |    12   |
| 6  |   345    |   2        |    12   |
| 7  |   467    |   3        |    14   |
----------------------------------------

1 个答案:

答案 0 :(得分:1)

You can use CAST with CONCAT, e.g.:

UPDATE table
SET group = CAST(CONCAT(company_id, city_id) AS INTEGER)
WHERE group IS NULL;

If group column is of type varchar only then you don't need to use CAST, e.g.:

UPDATE table
SET group = CONCAT(company_id, city_id)
WHERE group IS NULL;

This will make sure the value of group is unique for any combination of company_id and city_id.

Here's the documentation for CAST and CONCAT.