2

I have a table with data we've collected from various sources. It's got the item name, the source and the source's value.

The table looks like the following:

id name source value
1 abc web 1
2 abc print 2
3 xyz print 8
4 xyz web 9

Using the JSON_OBJECTAGG() function, I can group the sources together based on the name:

SELECT name, JSON_OBJECTAGG(source, value) AS data
FROM testStuff
GROUP BY name

This correctly gives:

name data
abc {"web":1, "print": 2}
xyz {"print":8, "web": 9}

Now, I want to run that query, but with a filter on the price/source, so I ran the following query:

SELECT name, JSON_OBJECTAGG(source, value) AS data
FROM testStuff
GROUP BY name
HAVING JSON_CONTAINS(data, 2, '$.print')

This seems to work, but there's a slight issue:

name data
abc {"web":1, "print": 2}}

Why is there suddenly an extra } at the end of the JSON data? The HAVING clause is correctly filtering the rows, but why does it modify the result data?

Online demo: https://sqlfiddle.com/mariadb/online-compiler?id=ccf1041c-3ada-4fc9-bd77-2b0fe1428392

I'm not sure what version of MariaDB that site uses, but testing this on my local computer using MariaDB 10.11.9 gives the same results.

EDIT: It seems I can fix this by using:

SELECT name, JSON_OBJECTAGG(source, value) AS data
FROM testStuff
GROUP BY name
HAVING JSON_CONTAINS(JSON_OBJECTAGG(source, value), 2, '$.print')

I just was trying to avoid writing the JSON_OBJECTAGG() multiple times. Also, while this fixes the issue, I still am curious as to why this was an issue in the first place.

EDIT 2: Another "fix" is to replace JSON_OBJECTAGG() with GROUP_CONCAT().

The following returns the correct data:

SELECT name,
    REPLACE(GROUP_CONCAT(JSON_OBJECT(source, value)), '},{', ',') AS data
FROM testStuff
GROUP BY name
HAVING JSON_CONTAINS(data, 2, '$.print')
gen_Eric
  • 121
  • 4

1 Answers1

0

The SQL in this query is correct, the issue here is a bug in MariaDB itself. (Link: https://jira.mariadb.org/browse/MDEV-23068)

I didn't open this bug report, it was created July 2020!

Hopefully this bug gets addressed in a future release of MariaDB.

gen_Eric
  • 121
  • 4