使用MySQL JSON字段联接表 [英] Using MySQL JSON field to join on a table

查看:2027
本文介绍了使用MySQL JSON字段联接表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储ID列表的json字段(我不知道这是最佳实践),我想知道是否可以在此JSON字段上使用do操作并在sql中使用它们.

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

以下是我要实现的虚构示例,这样的事情可行吗?

Below is a fictitious example of what I'm trying to achieve, is something like this doable?

CREATE TABLE user (
    user_id INT,
    user_name VARCHAR(50),
    user_groups JSON
);

CREATE TABLE user_group (
    user_group_id INT,
    group_name VARCHAR(50)
);

INSERT INTO user_group (user_group_id, group_name) VALUES (1, 'Group A');
INSERT INTO user_group (user_group_id, group_name) VALUES (2, 'Group B');
INSERT INTO user_group (user_group_id, group_name) VALUES (3, 'Group C');

INSERT INTO user (user_id, user_name, user_groups) VALUES (101, 'John', '[1,3]');

使用上述数据,我希望创建一个查询,使我得到如下结果:

With the above data I would like to fashion a query that gives me the results like this:

user_id | user_name | user_group_id | group_name|
-------------------------------------------------
101     | John      | 1             | Group A
101     | John      | 3             | Group C

下面我想一些伪风格的SQL,尽管我仍然不知道这是否可行,或者我将使用mysql提供的JSON函数实现这一目的

Some psuedo style SQL I'm thinking is below, though I still have no clue if this is possible, or what JSON functions mysql offers I would use to achieve this

 SELECT 
       u.user_id, 
       u.user_name, 
       g.user_group_id
       g.group_name
   FROM users u
   LEFT JOIN user_group g on g.user_group_id in some_json_function?(u.user_groups)

让我知道问题是否很清楚.

Let me know if the question isn't clear.

推荐答案

借助Feras的评论和一些摆弄:

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.

这篇关于使用MySQL JSON字段联接表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆