1
I have 3 tables in a library database. One is the member table, with the age of that member and one PRIMARY KEY. The second table, book, has a PRIMARY KEY isbn and the rest of the attributes authors and publishing house. The third table is a borrowed table, where it has the attributes isbn, as being a foreign key for the isbn attribute of the table book and the attribute member, being a foreign key of the member attribute.
CREATE TABLE livro(
isbn BIGINT PRIMARY KEY,
autores VARCHAR(25) NOT NULL,
editora VARCHAR(20) NOT NULL
);
CREATE TABLE emprestado(
num_membro INT NOT NULL,
isbn BIGINT NOT NULL,
FOREIGN KEY (num_membro) REFERENCES membro(num_membro),
FOREIGN KEY (isbn) REFERENCES livro(isbn));
I need to make a query to find the authors who had books taken for loan more than 5 times, and group them by publisher.
I made two ways:
SELECT l.editora, l.autores
FROM emprestado e INNER JOIN livro l ON e.isbn = l.isbn
WHERE (SELECT COUNT(l.autores)
FROM emprestado e INNER JOIN livro l ON e.isbn = l.isbn) > 5
GROUP BY l.editora, l.autores;
In this first case, the table also ends up returning other authors who have not had books picked more than 5 times.
SELECT l.editora, l.autores
from livro l JOIN emprestado e ON e.isbn = l.isbn
GROUP by l.editora, l.autores
HAVING COUNT(l.autores) > 5;
This second case, is not returned the authors in which their books have different publishers, that is, even if these authors have books taken more than 5 times, if their publishers are different it does not appear.
I would like to know how to make my query return the authors who had books picked more than 5 times, both having equal publishers, as distinct.
Grateful!!
I believe your joint condition
ON e.num_membro = l.isbn
is wrong, shouldn’t beON e.isbn = l.isbn
? In the second query I believe you should not includeautores
in its GROUP BY clause.– anonimo
I saw the wrong JOIN and tidied up (thanks), but still did not show the author that has different publishers. About the second query, I took l.authors from GROUP BY, it informs me "42803 column"l. authors" must appear in the GROUP BY clause or be used in an Aggregate Function", and even if I take this l.authors also from SELECT, it still does not return me those publishers of the authors I want, only the one that has the same publisher.
– Blavk