I am currently working on a MYSQL project which has a few fairly standard many to many relationship.
I’ve shown a greatly simplified relationship table to aid my example.
table: book_authors
ID BOOKS AUTHORS
1 1 4
2 1 5
3 4 4
4 4 5
5 2 6
6 2 1
7 2 5
8 3 6
9 3 5
10 3 1
12 5 2
13 6 2
14 7 5
What I’m looking to achieve is to be able to select all books which have specified authors, and only get the books which match all of the supplied authors. The number of authors requested each time is also variable.
So if i’m looking for all books written by author 4 and author 5, I’ll get result of books 1 and 4 only. If im looking for books written by author 5 only, i’ll get book 7 only.
I don’t think there’s a very smooth way to do this, but if performance isn’t a big concern, you can exploit MySQL’s
GROUP_CONCATfunction, and write this:(The
WHEREclause isn’t even needed for correct results, but it makes the query less gratuitously expensive.)