【问题标题】:MySql json reverse searchMySql json反向搜索
【发布时间】:2020-07-28 14:54:16
【问题描述】:

我有一个 MySQL 表,其中有一列类型为 json。此列的值是 json array 而不是 json object。我需要找到该表的记录,其 json 列的至少一个值是给定字符串/短语的子字符串。 假设表格如下所示:

create table if not exists test(id int, col json);
insert into test values (1, '["ab", "cd"]');
insert into test values (2, '["ef", "gh", "ij"]');
insert into test values (3, '["xyz"]');

如果输入字符串/短语是“acf ghi z”,则必须返回第二列作为结果,因为“gh”是输入的子字符串。我读了很多关于json_contains、json_extract、json_search 甚至json_overlaps 的文章,但无法解决这个问题。
检索相关行的正确 sql 语法是什么?

MySQL 版本为 8.0.20

【问题讨论】:

    标签: mysql sql json


    【解决方案1】:

    您可以使用json_table() 将 JSON 数组提取为表中的行。然后过滤:

    select *
    from test t cross join
         json_table(t.col, '$[*]' columns (str varchar(255) path '$')) j
    where 'acf ghi z' like concat('%', j.str, '%');
    

    Here 是一个 dbfiddle。

    【讨论】:

    • 此查询在 MySQL 中运行良好,但是当我使用 MariaDB4j 运行它进行单元测试时,我收到此错误 java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(t.col, '$[*]' columns (str varchar(255) path '$')) j where 'acf ghi z' like concat('%''。据我所知,MariaDB4j 向后兼容 MySQL,2.4.0 版本与 MySQL 中的json_table() 外观相差甚远。我怎样才能摆脱这个错误?谢谢。
    • @user2041057 。 . .您应该将此作为一个新问题提出。这个问题显然是关于 MySQL 的。
    • 我在another thread 中询问过,看来MariaDB 和MariaDB4j 不支持json_table()。是否可以在没有json_table() 的情况下重写上述查询以与MariaDB4j 兼容?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 2021-03-02
    • 2021-01-28
    • 2021-08-11
    相关资源
    最近更新 更多