Trying to do something on the lines of:
Table Entities
id | timestamp
---------------
1 | 2012-06-05 12:00:00
Table Attributes
entity_id | attribute
---------------------
1 | a
1 | b
What i'd like to be able to do:
select entity.id, entity.timestamp from entities entity join attributes on entity.id = attribute.id where entity.has.attributes a and b
The result set would look woeful now, but assume it has other columns on the entities table that will make sense. So the result set would be:
id | timestamp
--------------
1 | 2012-06-05 12:00:00
I looked at other posts on filtering one-many join relationships that end up using a count and distinct to solve very specific niche cases ( Filter a one-to-many query by requiring all of many meet criteria ) but I am hoping there's a cleaner, more generic solution to this.
Going to continue working away and I'll post back a solution if I can beat stackoverflow to it :)
This is what I have working so far. As pointed out, it's not pretty and I would daresay not performant, but I am going to look into full text search indices to see what they can offer.
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%';
But this assumes that you have the order by clause in the aggregation. If you choose to leave that out, this should work:
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%';
Very brittle, will break if your search attributes have kangaroo-word-like relationships. But, this will have to do for now.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.