Using MySQL JSON field to join on a table

Solution 1:

With the help of Feras's comment and some fiddling:

  SELECT 
       u.user_id, 
       u.user_name, 
       g.user_group_id,
       g.group_name
   FROM user u
   LEFT JOIN user_group g on JSON_CONTAINS(u.user_groups, CAST(g.user_group_id as JSON), '$')

This appears to work, let me know if there's a better way.

Solution 2:

Funny, I got to the opposite solution compared to Kyle's.

I wrote my query like this:

SELECT 
       u.user_id, 
       u.user_name, 
       g.user_group_id,
       g.group_name
   FROM user u
   LEFT JOIN user_group g on JSON_UNQUOTE(JSON_EXTRACT(u.user_groups, '$')) = g.user_group_id;

It also works, and this solution doesn't need any transforming on the right side of the expression, this could provide a benefit in query optimizing in certain cases.

Solution 3:

For arrays like ["1", "2", "3"] that values are in string type, JSON_SEARCH function is the way for your question:

SELECT 
   u.user_id, 
   u.user_name, 
   g.user_group_id
   g.group_name
FROM users u
LEFT JOIN user_group g ON (JSON_SEARCH(u.user_groups, 'one', g.user_group_id))

JSON_CONTAINS function does not return true for integers as candidate parameter:

SELECT JSON_CONTAINS(CAST('["1", "2", "3"]' AS JSON), CAST(1 AS JSON), '$')

returns 0 (false). You need to change it to this:

SELECT JSON_CONTAINS(CAST('["1", "2", "3"]' AS JSON), CAST(CONCAT('"', 1, '"') AS JSON), '$')

But JSON_SEARCH can find the result:

SELECT JSON_SEARCH(CAST('["1", "2", "3"]' AS JSON), 'one', 1)

returns "$[0]" that means "true".