0

I have a json field in mysql called column_info. Here's an example value:

[{"id": ["132605", "132750", "132772", "132773", "133065", "133150", "133185", "133188", "133271", "133298"]}, 
 {"number": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]}, 
 {"id": ["1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]}
]

Is it possible to do a query that does the following:

keys = ['id', 'number', 'id']
SELECT * FROM `column_info` WHERE JSON(??) = keys

2 Answers 2

1

Try:

SELECT `column_info`
FROM
  `table`,
  (SELECT @`keys` := '["id", "number", "id"]') `init`
WHERE (
  SELECT
    JSON_ARRAYAGG(
      JSON_UNQUOTE(
        JSON_EXTRACT(
          JSON_KEYS(`der`.`keys`),
          '$[0]'
        )
      )  
    )
  FROM
    JSON_TABLE(
      `column_info`,
      '$[*]'
      COLUMNS(
        `keys` JSON PATH '$'
      )  
    ) `der`
) = CAST(@`keys` AS JSON);

See db-fiddle.

Sign up to request clarification or add additional context in comments.

1 Comment

wow, that's pretty complex for doing a json query. Thanks for sharing. Unfortunately, I'm using mysql5.7, which doesn't support some of the above, but I tested it in the db-fiddle and it's pretty neat.
0

What version of MySQL are your running?

If it's v8, you can try JSON_CONTAINS()

https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.