I have groups that have a jsonb field – targets
my sql
SELECT DISTINCT groups.*
FROM groups
WHERE groups.user_id = 1 AND (
EXISTS (
SELECT * FROM jsonb_array_elements(targets) as a
WHERE a->>'name' ~* 'gender|age'
)
)
this will return groups that contain only gender or only age, or both gender and age together.
How to fix it so that it returns only groups that have both gender and age
my jsonb field targets looks like this
[{"name"=>"gender", "value"=>"0"}, {"name"=>"age", "value"=>"1"}]
2
Answers
You can achieve this by using the
GROUP BY
andHAVING
clauses, ensuring the presence of both elements by employing thecount()
function and the case clause :Demo here
You can use
jsonb_path_exists
. See the docs.