我有2个表:people和people_tag。
每个人在people_tag表中都有3个标签。
我想执行特定查询。
表(我用help django ORM创建这个表):
create table people (
id serial primary key
);
create table people_tag (
id serial primary key,
people_id serial references people(id),
tag text,
threshold integer
);
原始查询示例(我需要结果):
select people_id from (
select
people_id,
array_agg(tag) as tags from people_tag where threshold >= 40 group by people_id
) as t
where 'man' = ANY(tags) and ('tall' = ANY(tags) or 'short' = ANY(tags)) and 'thin' = ANY(tags);
我在django中尝试:
PeopleTag.objects.values_list('people_id').annotate(ArrayAgg('tag')).filter(threshold__gte=min_threshold)
得到:
SELECT "peopletag"."people_id", array_agg("peopletag"."tag") AS "tag__arrayagg" FROM "peopletag" WHERE "peopletag"."threshold" >= 70 GROUP BY "peopletag"."people_id";
如何为过滤器标签制作子查询(tag__arrayagg)?我知道如何进行过滤(使用.extra(where = ...)),但不能进行子查询。
结果我需要人ID阵列。
游乐场:http://sqlfiddle.com/#!15/97d788/16
谢谢。