如何使用count()函数为两个关系表编写mysql查询以显示所有数据?

如何使用count()函数为两个关系表编写mysql查询以显示所有数据?,mysql,sql,Mysql,Sql,表类别 category_id category_name 1 category-1 2 category-2 3 category-3 4 category-4 5 category-5 主键:类别id 表产品 product_id product_name ref_category_id product_status 1

类别

category_id    category_name
 1               category-1
 2               category-2
 3               category-3
 4               category-4
 5               category-5
主键:类别id

产品

product_id   product_name   ref_category_id  product_status

1             xxxx              1                Available
2             xxxx              2                Not Available
3            xxxxx             3                 Available
4            xxxxx             1                 Available
5            xxxxx             1                 Not Available
主键:产品标识 外键:参考类别id参考类别(类别id)

我想编写一个sql查询来显示以下结果:

Category_name   total_available_products_for_this_category

category-1                          2
category-2                          0
category-3                          1
category-4                          0
category-5                          0

请帮助我。

您可以在Mysql中使用
sum()
中的表达式,然后sum将对表达式返回的布尔值(0/1)求和,您可以根据您的条件进行计数

select c.* ,coalesce(sum(p.product_status = 'Available'),0)
from category c
left join product p on(p.ref_category_id = c.category_id )
group by c.category_id
使用
coalesce()
显示0而不是NULL

根据评论编辑

如果您使用count(*),这将统计每个类别组的所有关联(产品),而不考虑状态值,如果您仍要坚持使用count,则必须在其中使用
CASE
语句,如
count(当p.product\u status='Available'然后1 end时的CASE)
因此,当产品具有
可用
产品的
状态
时,将其计数为其他明智的忽略计数,因此这就是我所拥有的,因为我使用了带表达式的求和,不带
CASE
语句

select c.* ,
count(case when p.product_status = 'Available' then 1 end)
from category c
left join product p on(p.ref_category_id = c.category_id )
group by c.category_id
编辑2

使用
count(distinct p.product\u id)
只计算每个类别的不同产品,可以获得相同的结果,现在我不在求和函数中使用任何条件,也不在count中使用
CASE
语句,也只使用
count(distinct p.product\u id)
,但是我没有直接连接产品表,而是使用子查询从产品表中获取所有产品,其中
product\u status='Available'
,因此子查询将只返回可用的产品,然后我将子查询的此结果集与category table连接以获取计数

select c.* ,
count(distinct p.product_id)
from category c
left join
( select * from 
product where product_status = 'Available'
) p
on(p.ref_category_id = c.category_id )
group by c.category_id
希望它能让你对使用count有更清晰的认识


谢谢,但是计数函数有什么问题吗?如果我使用计数函数,那么它就是全部计数。你能给我一些很好的解释吗,那么它对我来说会很好。:-)非常感谢您能很好地理解我。我得到了我的答案。但我想知道更多关于count()函数的问题,而不使用条件。当您找到一些好的答案时,请通知我。在沙阿拉,我们将得到完美的答案。@user3909926 inshaalah我会让您知道,这是我最后一次尝试给你的想法,仍然使用它与计数见我的最后一次编辑的答案