2

I am storing data in standard tables in a MariaDB, but would like to return records from related tables as a JSON string.

What I intend to do is have a function where I can pass in exerciseId and the function returns a JSON string of all related exerciseMuscle records, meaning each exercise record returned by a stored proc can also include nested data from child tables.

I have been able to create JSON records using COLUMN_JSON and COLUMN_CREATE but can only get this to return as a set of individual records, rather than an array of JSON values as a need. The SQL I'm using is:

select
    e.id, 
    CONVERT(COLUMN_JSON(COLUMN_CREATE(
        'role', em.muscleRoleName, 
        'muscle', em.muscleName
    )) USING utf8) as musclesJson
from
    exercise e
    inner join exerciseMuscle em
            on e.id = em.exerciseId
where
    e.id = 96;

This returns:

| id | musclesJson 
| 96 | {"role":"main","muscle":"biceps"}
| 96 | {"role":"secondary","muscle":"shoulders"}

When what I want is:

| id | musclesJson 
| 96 | [{"role":"main","muscle":"biceps"},{"role":"secondary","muscle":"shoulders"}]

Is it possible to return multiple results in one row without having to iterate through the results and build it manually? If I add a group by to the SQL then the JSON only includes the first record.

2
  • Which MySQL version are you using? Commented Oct 9, 2016 at 12:00
  • MariaDB 10.0.24, just changed tag Commented Oct 9, 2016 at 12:01

1 Answer 1

3

Turns out it was GROUP_CONCAT that I needed, and specifying a comma as the delimiter. So changing my SQL to:

select
    e.id, 
    CONVERT(
        GROUP_CONCAT(
            COLUMN_JSON(
                COLUMN_CREATE(
                    'role', em.muscleRoleName, 
                    'muscle', em.muscleName
                )
            )
            SEPARATOR ','
        ) USING utf8) as muscles 
from
    exercise e
    inner join exerciseMuscle em
            on e.id = em.exerciseId
where
    e.id = 96;

Returns:

| id | musclesJson 
| 96 | {"role":"main","muscle":"biceps"},{"role":"secondary","muscle":"shoulders"}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.