L
L
lindou2019-12-21 17:51:51
MySQL
lindou, 2019-12-21 17:51:51

Select by condition, but what is not found should be specified as zero?

Good evening!
Please correct the question if it is not correct.
How can one query get a list of records so that all records are displayed, but only the record that matches the condition has a count?

select c.color_id, c.color_name, count(p.product_id) as total
from color as c
left join product as p on c.color_id = p.color_id
where p.color_id = 2
group by c.color_id

In this example, the result will be
{
    color_id = 2
    color_name = red
    total = 47
}

But I would like to display the rest of the colors, only with total = 0, respectively.
How can this be implemented?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Game Master, 2019-12-21
@lindou

https://www.db-fiddle.com/f/emqonUSGZKx36N7jNVN1Ew/2

select c.color_id, c.color_name,
       count(p.product_id) as total,
       count(case when c.color_name = 'red' then 1 end) as red_cnt
from color as c
         left join product as p on c.color_id = p.color_id
group by c.color_id, c.color_name;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question