问题
I'm trying to find all recipes in a certain category, where the key/value data is recorded in a PostgreSQL's jsonb column (and the value is saved as an array).
For example, say I have "data" as my jsonb column in the "recipes" table, and I have three entries like so:
"Recipe 1" contains a "data" with key/value of: "category_ids"=>[123, 4059]
"Recipe 2" contains a "data" with key/value of: "category_ids"=>[405, 543]
"Recipe 3" contains a "data" with key/value of: "category_ids"=>[567, 982]
I want to retrieve only items that contain the "405" category id value (i.e. only Recipe 2 above)
This is what I have so far using Ruby on Rails to query the PostgreSQL database:
Recipe.where("(data ->> 'category_ids') LIKE '%405%'")
However, that retrieves both "Recipe 1" and "Recipe 2" because they both contain "405" text.
What query should I use to correctly retrieve recipes with the "405" category id only?
回答1:
You can also directly use IN along with json_array_elements:
Recipe.where("'405' IN (SELECT json_array_elements(data->'category_ids')::text)")
And if your column is a jsonb column, you can similarly do:
Recipe.where("'405' IN (SELECT jsonb_array_elements(data->'category_ids')::text)")
回答2:
you need ANY
function. Something like
select * from t where '405' = any (
ARRAY(
SELECT e::text FROM json_array_elements(data->'category_ids') e
)
);
or
select * from t where '405' = any (
ARRAY(
SELECT e::text FROM jsonb_array_elements(data->'category_ids') e
)
);
if your type is jsonb (higher than 9.3 postgres version)
http://sqlfiddle.com/#!15/1a895/1
回答3:
You can use unnest function
available. More details can be check here : Postgresql Functions & Operators.
来源:https://stackoverflow.com/questions/37123173/using-jsonb-postgresql-how-do-i-retrieve-items-with-a-certain-value-thats-sa