我的数据库有这个要求,如下所示

我想获取3列requestTypeCategoryGroupreadStatus列的计数

结果将显示所有requestTypecategoryGroup,如果readStatus为false,则显示其计数,如果在同一readStatus中所有requestType为true,则返回0。

同样,如果requestTypeNULL并且在同一categoryGroup中为空白(来自表A,子类别ID 12和13来自表B中的相同categoryGroup),则categoryGroup应该显示为BLANK并应保存( readStatus=0)NULL和BLANK

mysql - 获取未读邮件的数量-LMLPHP

我编写的查询仅返回有关readStatus=false的列和计数,并显示其总数。

select coalesce( m.requestType, "") as requestType,
  count(m.messageId) as count,
  s.categoryGroup categoryGroup
from mb_message m
join mb_subcategory s on m.subCategoryId = s.subCategoryId
where m.readStatus=0
and m.storeId = ?
and countryCode= ?
and m.modifiedDate >= ?
group by m.requestType, m.subCategoryId;


上述查询的预期结果是:

mysql - 获取未读邮件的数量-LMLPHP

最佳答案

我会做类似的事情:

select
  requesttype,
  sum(cnt) as cnt,
  categorygroup
from (
  select
    case when a.requesttype is null or a.requesttype = ''
         then 'BLANK' else a.requesttype end as requesttype,
    case when a.readstatus = 0 then 1 else 0 end as cnt,
    b.categorygroup
  from tablea a
  join tableb b on b.subcategoryid = a.subcategoryid
) x
group by requesttype, categorygroup

09-25 19:16