Skip to content
Advertisement

Mysql: Update json column with values from different table/column

I’ve been trying to update the below neighbors column in location table as json object, as seen below, but cannot get this even remotely close to working in any way. Any idea on the query syntax?

Original table:

nearby (this is join table where place & nextdoor refer to location.id)

Expected after update:

Advertisement

Answer

Give this a shot. It’s tested on MySQL 8. I broke it down into steps so you can test each CTE on after the other to see how it comes together.

Tables

Update query

Result

id | name | neighbors                                                                                                                                                   
-: | :--- | :-----------------------------------------------------------------------------------------------------------------------------------------------------------
 1 | loc1 | {"g1": "[{"name": "loc2", "distance": "500m"},{"name": "loc3", "distance": "900m"}]"}                                                       
 2 | loc2 | {"g3": "[{"name": "loc1", "distance": "500m"}]", "g4": "[{"name": "loc3", "distance": "100m"},{"name": "loc4", "distance": "80m"}]"}
 3 | loc3 | null                                                                                                                                                        
 4 | loc4 | null                                                                                                                                                        
 5 | loc5 | null                                                                                                                                                        

Example

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=789fb79d10b745414ca7270a5a6ef004

Another one with an example of json_extract after the update has taken place.

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=fe651372ca754cc05eab842d6fced9a3

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement