mysql - 如何在 MySQL 中搜索 json 值数组上的数据

标签 mysql sql json

我从未使用过 json data 在我的数据库中存储任何值,现在的情况促使我使用它。

下面是我将其存储到 MySQL 数据库中的 json 格式

{
    "wrestling_board": [{
        "Price": "400",
        "Quantity": "1",
        "Amount": "400"
    }],
    "sign_board": [{
        "Price": "200",
        "Quantity": "1",
        "Amount": "200"
    }],
    "total": [{
        "Price": null,
        "Quantity": null,
        "Amount": "600"   <-- total price
    }]
}

Here is MySQL Demo:

如何搜索所有结果 其中total.amount > 3000

最佳答案

更新: 如果您的字段是 json,您可以使用如下查询:

select 
    customer_name,company_name,email,quotation_data
from 
    sent_quotation_data1
where 
    cast(                                             --> as you want to check numeric operator I use cast to unsigned
        (replace(                                     --> as your data is between " I use replace to remove them
            quotation_data->"$.total[0].Amount"       --> Here you can extract json data
        ,'"','')) as unsigned
    ) > 3000;

MySQL Fiddle Demo

<小时/>

我认为一种方法是像这样使用REGEXP:

select 
   customer_name,company_name,email,quotation_data 
from 
   sent_quotation_data
where 
   quotation_data REGEXP '"total":.+"Amount":"(3[0-9][0-9][1-9]|[4-9][0-9]{3}|[1-9][0-9]{4,})"';

MySQL Fiddle Demo

"total":                     --> Finding total between " then :
.+                           --> Some characters
"Amount":"                   --> Finding Amount between " then : then "
(                            --> start a combination
    3[0-9][0-9][1-9]         --> accepting range of 3001-3999
    |                        --> or
    [4-9][0-9]{3}            --> accepting range of 4000-9999
    |                        --> or
    [1-9][0-9]{4,}           --> accepting range of 10000-...
)                            --> end of combination
"                            --> following by "

关于mysql - 如何在 MySQL 中搜索 json 值数组上的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48040030/

相关文章:

php - 使用 PHP 从 MySQL 数据库中获取特殊字符

sql - 选择 SQL 查询以从 ntext 列获取 xml 节点值?

javascript - 我想使用 node.js 触发对 mysql 的顺序查询,但只有最后一个被触发

ios - 使用 NSJSONSerialization.JSONObjectWithData() 解析数据但无法仅访问数组组字符串

sql - 选择嵌套 JSON 数组包含特定值的行

php - 包括 foreach 循环数据输出的复选框

标签系统的 MySQL 模式和 CRUD 查询

mysql - 在MySQL中选择多列

sql - T-SQL 唯一标识列作为复合主键的一部分

c# - 序列化 Dictionary<string,Type> 并从 JSON 字符串中删除键/值