1

In postgres I am fairly sure you can do something like this

SELECT
  authors.stage_name, 
  count(select id from books where books.author_id  = authors.id) 
FROM
  authors,
  books;

Essentially, in this example I would like to return a list of authors and how many books each has written.... in the same query.

Is this possible? I suspect this approach is rather naive..

Thanks :)

2 Answers 2

1

Well, for one thing, it returns a Cartesian product of all authors to all books, regardless of whether that author wrote that book.

Here's how I'd write a query to get the result you say you want:

SELECT a.stage_name, COUNT(b.id)
FROM authors a
  LEFT OUTER JOIN books b ON (a.id = b.author_id)
GROUP BY a.id;

You need to learn how to write join queries if you use SQL. The join is to SQL what the loop is to application programming languages. I.e. it's a fundamental programming construct that you need to know.

Sign up to request clarification or add additional context in comments.

Comments

0

How about using a join:

SELECT authors.stage_name, count(*) 
FROM authors INNER JOIN books on books.author_id = authors.id
GROUP BY authors.stage_name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.