For a school project, I should do queries on this Library model.
I’ve done good so far, but now I’m stuck on this question: “List a number of copies per book”.
Here’s what’ve done and not working as it should:
SELECT liv_titulo, ( 
    SELECT count(exe_cod)
    FROM exemplar
    GROUP BY liv_cod
    ORDER BY COUNT(exe_cod) desc) Quantidade
FROM livro INNER JOIN exemplar USING (liv_cod);
Advertisement
Answer
I think the technique you wanted to use is a correlated subquery:
you need a
WHEREclause in the subquery so it only takes into account theliv_codefrom the current row in the outer queryno
GROUP BYclause is needed in the subquery; it should return a scalar value (just one row and one column, that contains the count of matching rows from tableexamplar)there is no need for a
joinin the outer query
Code:
SELECT 
    liv_titulo, 
    ( 
        SELECT count(*)
        FROM exemplar e
        WHERE e.liv_cod = l.liv_cod  -- correlation
    ) Quantidade
FROM livro l;