G
G
Glory2022-02-10 19:53:14
SQL
Glory, 2022-02-10 19:53:14

How to properly display all records with related entity count?

we had a request. It shows the product categories and the number of products in each directory. but it worked so that in the issue only those categories that have a product. And it is necessary to make so that all categories showed.
Initial request:

select categories.name,
       categories.id,
       categories.parent_id,
       categories.image,
       categories.slug,
       categories.sort,
       categories.active,
       categories.created_at,
       categories.updated_at,
       categories.weight,
       categories.dimensions,
       categories.seo_title,
       categories.seo_description,
       categories.work_desc,
       count(*) products_count
        from `categories`
           left join `master_product_categories` on `master_product_categories`.`category_id` = `categories`.`id`
           left join `master_products` on `master_product_categories`.`master_product_id` = `master_products`.`id`
where `master_product_categories`.`published` = 1
  and `master_product_categories`.`deleted_at` is null
  and `master_products`.`group_id` is null


in the issue only those categories in which there are goods.
before that there was a join - this was replaced with a left join,

but it is necessary that all categories are included in the selection. and it doesn't matter if there are goods.

why doesn't it work for me?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question