A
A
Andriy12182016-06-19 16:08:01
SQL
Andriy1218, 2016-06-19 16:08:01

How to set a default value for a column in a table?

I have three tables: Book(Id), Topic(Id), BookTopic(BookId, TopicId). There is a query that for each Topic returns the number of Books in this Topic:

SELECT T.Id, T.TopicName, count(BT.TopicId) AS 'BooksCount' 
FROM Topic T, BookTopic BT
WHERE T.Id = BT.TopicId
GROUP BY T.Id, T.TopicName

But there is a problem: if no book is associated with a topic, then such a topic is not returned. And I would like such a topic to be returned with the BooksCount=0 value. How can I do that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tommy87, 2016-06-21
@Andriy1218

The question is incorrect in the header, but what you are asking to do is like this:
SELECT T.Id, T.TopicName, count(BT.TopicId) AS 'BooksCount'
FROM Topic T
LEFT JOIN BookTopic BT on
T.Id = BT.TopicId
GROUP BY T.Id, T.TopicName

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question