I have more or less the following table:
list_id | key |
---|---|
1 | a |
1 | b |
1 | c |
2 | d |
2 | e |
3 | f |
3 | g |
… | … |
Given a certain key or set of keys, what sql query will return all the keys that share a given list_id
. For example, given key a, I want to return a, b, c. Given a,d, I should get back a,b,c,d,e.
2
Answers
On option is to select the list_ids you want in a subquery / cte and from there filter the rest, e.g.
Demo:
db<>fiddle
You could use
exists
:If two keys might match on more than one list_id, then you would probably need
select distinct key
to avoid duplicates in the resultset (although that’s not the case for your example data).This query would take likely advantage of an index on
mytable(key, list_id)
(ormytable(list_id, key)
depending on the cardinality of the two columns).