mysql json where 子句

nig*_*fly 4 mysql json sqldatatypes mysql-8.0

我有一个表,表 PRICING_DATA 中包含以下 json 数据类型列

pricingJson type json nullable
Run Code Online (Sandbox Code Playgroud)

我正在使用sql来查询表。

select * from `PRICING_DATA` where `pricingJson`->"$.product.productFamily" = "Compute Instance";
Run Code Online (Sandbox Code Playgroud)

示例 json 数据如下所示

{
"product": {
    "productFamily": "Compute Instance",
    "attributes": {
        "enhancedNetworkingSupported": "Yes",.....
Run Code Online (Sandbox Code Playgroud)

但查询没有返回任何行。我在这里做错了什么?

来自数据库的 Json 原始字符串似乎被转义了。

"{\"product\":{\"productFamily\":\"Compute Instance\",\"attributes\":{\"enhancedNetworkingSupported\":\"Yes
Run Code Online (Sandbox Code Playgroud)

我已经使用了下面的 json unquote,但它仍然没有给我任何行。

select * from `PRICING_DATA` where JSON_UNQUOTE(JSON_EXTRACT(pricingJson, "$.product.productFamily")) = "Compute Instance";
Run Code Online (Sandbox Code Playgroud)

Roc*_*mat 8

您需要“取消引用”JSON 字符串才能进行比较。

select * from `PRICING_DATA` where `pricingJson`->>"$.product.productFamily" = "Compute Instance";
Run Code Online (Sandbox Code Playgroud)

文档:https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#operator_json-inline-path


使用pricingJson->"$.product.productFamily"是简写

JSON_EXTRACT(pricingJson, "$.product.productFamily")
Run Code Online (Sandbox Code Playgroud)

它返回值,但作为带引号的字符串。所以:

SELECT pricingJson->"$.product.productFamily" FROM PRICING_DATA
Run Code Online (Sandbox Code Playgroud)

会返回:

+-----------------------------------------+
| pricingJson->"$.product.productFamily"  |
+-----------------------------------------+
| "Compute Instance"                      |
+-----------------------------------------+
Run Code Online (Sandbox Code Playgroud)

您需要使用该函数删除引号JSON_UNQUOTE(),并且 usingpricingJson->>"$.product.productFamily"是以下形式的简写:

JSON_UNQUOTE(JSON_EXTRACT(pricingJson, "$.product.productFamily"))
Run Code Online (Sandbox Code Playgroud)