MySQL select where JSON field property has value

情到浓时终转凉″ 提交于 2019-12-04 17:28:19

问题


How to write a basic MySQL query that has a WHERE on a property within a JSON data-type field? I don't see basic where clause q for json fields on SO.

Something like this, but of course these dont work:

SELECT * from my_table where meta_data->name = 'bob';

SELECT * from my_table where meta_data[name] IS NOT NULL;

回答1:


Some examples of how to query a json data type field:

SELECT * FROM users WHERE JSON_EXTRACT(meta_data, "$.first_name") = 'bob';

SELECT * FROM users WHERE JSON_EXTRACT(meta_data, "$.age") IS NOT NULL;

SELECT * FROM users WHERE JSON_EXTRACT(meta_data, "$.accepted_policy") = true;

With mysql 5.7.9 +

You can also just do this (shortcut for JSON_EXTRACT):

SELECT * FROM users WHERE meta_data->"$.first_name" = 'bob'

You might notice your json data results are "quoted". You could use JSON_UNQUOTE, or you could use this, which is a shortcut of JSON_EXTRACT & JSON_UNQUOTE:

SELECT meta_data->>"$.first_name" FROM users WHERE meta_data->>"$.first_name" IS NOT NULL

And to select data from within sub objects:

SELECT meta_data->>"$.address.tel" FROM users WHERE meta_data->>"$.address.street" = "123 Main St"

docs: https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html



来源:https://stackoverflow.com/questions/49053341/mysql-select-where-json-field-property-has-value

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