问题
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