mysql json where clause

▼魔方 西西 提交于 2021-02-07 10:11:59

问题


I have a table with the below json data type column in a table PRICING_DATA

pricingJson type json nullable

And I am using the sql to query the table.

select * from `PRICING_DATA` where `pricingJson`->"$.product.productFamily" = "Compute Instance";

The sample json data is like below

{
"product": {
    "productFamily": "Compute Instance",
    "attributes": {
        "enhancedNetworkingSupported": "Yes",.....

But the query is not returning any rows. What am I doing wrong here?

Json raw string from the db seems escaped.

"{\"product\":{\"productFamily\":\"Compute Instance\",\"attributes\":{\"enhancedNetworkingSupported\":\"Yes

I have used the below json unquote but still it is not giving me any rows.

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

回答1:


You need to "unquote" the JSON string in order to compare it.

select * from `PRICING_DATA` where `pricingJson`->>"$.product.productFamily" = "Compute Instance";

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


Using pricingJson->"$.product.productFamily" is shorthand for

JSON_EXTRACT(pricingJson, "$.product.productFamily")

which returns the value, but as a quoted string. So:

SELECT pricingJson->"$.product.productFamily" FROM PRICING_DATA

would return:

+-----------------------------------------+
| pricingJson->"$.product.productFamily"  |
+-----------------------------------------+
| "Compute Instance"                      |
+-----------------------------------------+

You need to remove the quotes with the JSON_UNQUOTE() function, and using pricingJson->>"$.product.productFamily" is shorthand for:

JSON_UNQUOTE(JSON_EXTRACT(pricingJson, "$.product.productFamily"))


来源:https://stackoverflow.com/questions/56188209/mysql-json-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!