尝试执行以下操作:
Table Entities
id | timestamp
---------------
1 | 2012-06-05 12:00:00
Table Attributes
entity_id | attribute
---------------------
1 | a
1 | b
我希望能做什么:
select entity.id, entity.timestamp from entities entity join attributes on entity.id = attribute.id where entity.has.attributes a and b
结果集现在看起来很糟糕,但假设它在实体表上有其他有意义的列。所以结果集将是:
id | timestamp
--------------
1 | 2012-06-05 12:00:00
我看了其他关于过滤一对多连接关系的帖子,最终使用计数和distinct来解决非常具体的利基情况(通过要求所有许多符合标准来过滤一对多查询),但我希望有一个更清晰,更通用的解决方案。
将继续工作,如果我能打败stackoverflow,我会发布一个解决方案:)
这是我到目前为止所做的工作。正如我所指出的那样,它并不漂亮,而且我敢说性能也不高,但我打算研究全文搜索索引,看看它们能提供什么。
select e.id, e.timestamp from entities e join
(select entity_id, string_agg(attribute, ',' order by attribute) as attr from attributes
group by entity_id) a
on e.id = a.entity_id where a.attr like '%a%b%';
但是这里假设在聚合中有order by子句。如果您选择忽略它,这应该可以工作:
select e.id, e.timestamp from entities e join
(select entity_id, string_agg(attribute, ',') as attr from attributes
group by entity_id) a
on e.id = a.entity_id where a.attr like '%a%' and a.attr like '%b%';
非常脆弱,如果你的搜索属性有袋鼠式的单词关系,就会破裂。但是,现在只能这样了。