Skip to content
Advertisement

JPA PostreSQL many to many relationship select and order by number of relationships

I have a many to many relationship between Article and Topic. I need to get all articles related to some topics and order them by the intersection between the given set of topics and the topics of a given article. The articles that have more topics in common with the given set of topics should be returned first.

So far I can retrieve the articles related to a given list of topics. But I don’t know how to achieve the ordering part. Where the articles with the most topics in common with the given set of topics go first.

Some pseudo SQL code of what I’m thinking would be:

In kotlin code it would be:

Advertisement

Answer

I finally got it. It wasn’t too difficult after all.

Just in case you want to test this:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement