简体   繁体   中英

Select decoded JSON data from joined MySQL tables

Could you write me please how to make selection from MySQL database if I have two tables with JSON data. One of them has following structure:

Table Trees
(id, name, value) - three columns

which includes following data

1,  trees, [{"name":"Oaktree","value":1,"target":null},{"name":"Appletree","value":2,"target":null},{"name":"Plumtree","value":3,"target":null}]
2,  length, [{"name":"10m","value":1,"target":null},{"name":"15m","value":2,"target":null},{"name":"20m","value":3,"target":null}]
3,  age, [{"name":"5y","value":1,"target":null},{"name":"10y","value":2,"target":null},{"name":"20y","value":3,"target":null}]

The second table has the following structure:

Table SelectedTrees
(properties) - only one column

which includes the following data

[{"id":"1","value":["1","3"]},{"id":"2","value":["1", "2", "3"]},{"id":"3","value":["2"]}]

it means selected data from Trees tables. id in properties column from selectedTrees coresponds to id column from Trees table. I would like to select from database real (json_decoded) values like:

Trees = Oaktree, Plumtree

Length = 10m, 15m, 20m

Age = 10y

How could I make this? Thanks in advance.

Jan

In a nutshell, this is not possible. Relational databases are built for quickly comparing constant values that they can index. JSON is just a string to MySQL, and any kind of partial string matching triggers a so-called table scan , which is essentially going to become freaking slow when you get serious amounts of data.

You COULD get it to work like this:

SELECT * FROM Trees
JOIN SelectedTrees
  ON properties LIKE CONCAT('"id":"', Trees.id, '"')

This is however just a hack that you should never want to use in any production system , and I advise against using it in a test system. Instead refactor your database so there's never going to be any JSON in there that you are going to match on in your queries . It's fine to store secondary data as JSON, just make sure the IDs and names are extracted before insertion, and then insert in separate columns in the database tables so the DB engine can do its relational magic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM