Skip to content
Advertisement

How to prevent duplicate rows in sql cross join

I have books, authors and links table. I want to get all books that has in their author at least one from chosen. Links is table with connections between them: if you want to set some book author you need to create row in links with foerign keys book_id, author_id. What I’m trying to do:

What i get

I want ot somehow get result without book duplicates, but I’m not sure that it is possible. What can I do only with sql commands in this case?

Advertisement

Answer

One method to avoid duplicate is to use exists with a correlated subquery rather than a join:

This displays books that match, whithout their authors.

Another (probably less efficient) approach is aggregation and group_concat() to put all matching authors in the same row:

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