0

What I have:

  • A mysql table, say table1
  • table1 contains two columns viz. id and data
  • id is int but the twist is data is JSON type and its keys are comparable
  • the table1 contains only one row (for the sake of this question)

table1

id data
1 {'1': 'content1', '2': 'content2', '3':'content3',.......,'10000':'content10000' }

What I want to have:

I want a query such that it returns me key-value pairs within a range of keys, say, 100 to 200.

What I'm getting on searching on internet:

Everywhere I got only the answers where one can get rows which have the values within a range, but here the case is I want values of keys within a range.

6
  • 1
    for starters which mysql version are you using? basically json is bad for such problems, mysql 8 has json_table which simplifies it somewhat, still json is bad if you want that information directly from mysql, store tem in a normal relational table and it gets easy
    – nbk
    Commented Mar 10, 2021 at 14:51
  • I'm using MariaDB 10.4 Commented Mar 10, 2021 at 15:33
  • Synthetic numbers list and JOIN.
    – Akina
    Commented Mar 10, 2021 at 15:50
  • @Akina the oath must be strings or not`?
    – nbk
    Commented Mar 10, 2021 at 16:19
  • @nbk Generated numbers will be used for to build JSON paths - so number during generation and string finally.
    – Akina
    Commented Mar 10, 2021 at 16:27

1 Answer 1

2

Possible realization:

WITH RECURSIVE cte AS ( SELECT @from num
                        UNION ALL
                        SELECT num+1 FROM cte WHERE num < @till )
SELECT CONCAT('key', num) `key`, 
       JSON_EXTRACT(test.val, CONCAT('$.key', num)) `value`
FROM test
CROSS JOIN cte
HAVING `value` IS NOT NULL;

fiddle

1
  • Thanks @Akina, learned something new today. Commented Mar 11, 2021 at 5:20

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.