1

I have two tables

BOOK(book_id, book_name)

and

COPY(copy_id, book_id, available(bool))

I want to have a query to display book_id, book_name, and COUNT(*) of all copies with the same book_id in COPY table that have available set to true. Sample query output should look like this:

1, BookA, 2
2, BookB, 4
3, BookC, 0

So BookA has two COPY tuples with available set to true. This is what I have so far, it doesn't work.

SELECT * FROM
(SELECT * FROM BOOK)book,
(SELECT book_id, COUNT(copy_id) FROM COPY)copy
WHERE book.book_id = copy.book_id;

2 Answers 2

2

Since bool values are 1 if true in MySQL, you can sum them up

SELECT b.book_id, 
       b.book_name, 
       sum(c.available) as copy_count
FROM book b
left outer join copy c on c.book_id = b.book_id
group by b.book_id

SQLFiddle demo

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

5 Comments

Good query for the case that copy id is an ID and it is unique.
This one doesn't display my third case in which BookC has 0 COUNT of available.
try changing sum(c.available) to sum(ifnull(c.available,0)). (although @juergend seems to be right)
Inner joins only display rows when they match in both tables. Outer joins will always display from one regardless of a match in the other.
0

Here's another variant:

SELECT b.book_id, 
       b.book_name, 
       count(c.available) as copy_count
FROM book b
left outer join copy c on c.book_id = b.book_id and c.available = 1
group by b.book_id

This is a little more efficient because the join doesn't include any of the rows with unavailable books, so it's a smaller intermediate table to process.

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.