If you are on 9.4 something like this might be what you are after:
select json_object(array_agg(id)::text[],array_agg(rw)::text[])
from( select id
, ( select to_json(array_agg(row_to_json(t)))
from (select typ,prop from bgb where id=b.id) t ) rw
from bgb b
group by id ) z;
You could use an inner join
to filter for rows that share a (p_id, k_id)
value with rows that have a (t_id, pos)
of (1,1)
(sqlfiddle):
select base.p_id
, base.k_id
, json_agg(base order by base.p_id, base.k_id, base.t_id, base.pos) as stats
from (
select p_id
, k_id
, t_id
, pos
from two
) base
join two as filter
on filter.t_id = 1
and filter.pos = 1
and filter.p_id = base.p_id
and filter.k_id = base.k_id
group by
base.p_id
, base.k_id;
Or an equivalent way using an exists
subquery (sqlfiddle):
select base.p_id
, base.k_id
, json_agg(base order by base.p_id, base.k_id, base.t_id, base.pos) as stats
from (
select p_id
, k_id
, t_id
, pos
from two
) base
where exists
(
select *
from two as filter
where filter.t_id = 1
and filter.pos = 1
and filter.p_id = base.p_id
and filter.k_id = base.k_id
)
group by
base.p_id
, base.k_id;
Updated to use json_agg
from @ErwinBrandstetter's answer.
Best Answer
You can't really do this unless you are using MySQL 5.7 and the
category
column is using the JSON datatype. If it is, you can use the JSON_CONTAINS function:Pay attention to the rules of containment:
We can see the issue with datatypes in this dataset: