Using MySQL JSON field to join on a table

后端 未结 3 705
盖世英雄少女心
盖世英雄少女心 2020-11-30 08:27

I have a json field that stores a list of ids (not best practice here I know), I want to know if it\'s possible to use do operations on this JSON field and use them in the s

相关标签:
3条回答
  • 2020-11-30 08:33

    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.

    0 讨论(0)
  • 2020-11-30 08:40

    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".

    0 讨论(0)
  • 2020-11-30 08:54

    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.

    0 讨论(0)
提交回复
热议问题