Home > Back-end >  How do I cast a JSON sub-value to an integer in MySQL?
How do I cast a JSON sub-value to an integer in MySQL?

Time:12-29

I currently have this

  UPDATE {$table}
            SET
                {$column} = JSON_SET(
                    {$column},
                    '$.{$jsonKey}',
                    {$column}->>'$.{$jsonKey}' * 100
                )

However the value inside the json will be a double. I would like it to be an integer. The code below results in a syntax error.

 UPDATE {$table}
            SET
                {$column} = JSON_SET(
                    {$column},
                    '$.{$jsonKey}',
                    {$column}->> CAST('$.{$jsonKey}' * 100 AS UNSIGNED)
                )

CodePudding user response:

You can combine JSON_EXTRACT with JSON_SET, and then CAST the extracted value to Integer.

UPDATE {$table}
SET
    {$column} = JSON_SET(
        {$column},
        '$.{$jsonKey}',
        CAST(JSON_EXTRACT({$column}, '$.{$jsonKey}') * 100 AS UNSIGNED)
    )
  • Related