dimanche 8 novembre 2015

sqlite: selecting from multiple tables with m:n relation

i have the following tables:

USER (ID, NAME)
BOOK (ID, TITLE)
USER_BOOK(USER_ID, BOOK_ID)
AUTHOR (ID, NAME, LASTNAME, LOCATION)
BOOK_AUTHOR(BOOK_ID, AUTHOR_ID)

Now i want to select all books with all authors of the selected books for a given user id.

I tried the following:

SELECT * FROM USER_BOOK 
    LEFT OUTER JOIN BOOK ON BOOK.ID = USER_BOOK.BOOK_ID
    LEFT OUTER JOIN BOOK_AUTHOR ON BOOK_AUTHOR.BOOK_ID = BOOK.ID
    LEFT OUTER JOIN AUTHOR ON AUTHOR.ID = BOOK_AUTHOR.AUTHOR_ID
    WHERE ID = ?

I expected the following result structure:

book id
book title
author 1
    id
    name
    lastname
    location
author 2
    id
    name
    lastname
    location
...

But what i got was the following:

user id
book id
book id
book title
author id
author lastname

user id
book id
book id
book title
author id
author lastname

And i have no idea how to handle that. i have no idea about sql at all unfortunately but from some tutorials i thought the joins are the correct operators to get what i want.

Actually i dont need the user id and the book id from the USER_BOOK table i just needed to get all the book id's which are in relation with the user. And next thing is why is the book information repeating for every author? its enough when i get the book informations once. And the most weird thing is that i just get the id and the lastname from author and not all columns of the table.

Aucun commentaire:

Enregistrer un commentaire