I have a table in the following format:
row_key extID tag val
------- ----- --- ---
1 1 A a
2 1 A b
3 1 B c
4 2 A d
5 2 C e
Now I want to have all extID’s where there are several pairs of (tag, val) with specific values, for example:
(tag, val) = (A,a) AND (tag, val) = (B,c)
or,
(tag, val) = (C,e)
The number of constrains can change.
I can think of several ways to do this:
- Perform a self-join for each constraint
- Do the searching (iteratively) in the caller program (multiple SQL queries)
- (Maybe?) write a SQL function to do this
- Nested SELECT clauses (passing to the outer level the “extID” and using
WHERE extID IN (SELECT extID FROM ...) - The only true solution that I just can’t find.
Which one would be the preferred (fastest and most elegant) way to do this? (Except, of course, “Surely, 5. is the correct answer.”)
I think a multiple SELF-join is quite elegant. However, I do not know if it is fast and comparatively memory-efficient.
Further, I would like to use a way that works with MySQL, PostgreSQL and SQLite without adaptation – That’s why I can’t use PIVOT afaiu.
UPDATE 1
since you haven’t mentioned that there can be duplicate combination of
tagandval,DISTINCTkeyword is needed.