Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort foreign keys by how many times they match with specified foreign key

I have a table with composite keys id and name, where id is foreign key to another table.

id name
1 a
1 b
1 c
2 b
2 f
3 b
3 c
3 f
4 f

And i need to sort which id-s have most matching ‘name’ values as id for example 1.
Here, result would be [3, 2] (id 4 doesn’t match one time), id3 matches 2 times (b and c) and id2 matches 1 time (b).

How would I query this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Ideally it would return ordered pairs of (id, match_count).

>Solution :

It can easily be done with a join and group by:

-- using id = 1 as reference

select t1.id, count(*) as match_count
from (select id, name from t where id <> 1) as t1
join (select name from t where id = 1) as t2 on t1.name = t2.name
group by t1.id
order by match_count desc
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading