包括COUNT()= 0的结果

时间:2015-09-07 08:24:30

标签: php mysql count

选择带有计数的表格字段。那部分是有效的。我还需要在计数为0的情况下包含结果

这就是我试过的

SELECT mallname, COUNT( * ) AS Count
FROM `malls`
INNER JOIN Mal_Client_Relationship ON Mal_Client_Relationship.m_Id = malls.m_Id
INNER JOIN clients ON Mal_Client_Relationship.id_user = clients.id_user
INNER JOIN dates ON dates.date_id = Mal_Client_Relationship.date_id
WHERE confirmcode = 'y' && EndDate >= CURRENT_DATE( ) || HAVING count(*) = 0
GROUP BY `mallname`
ORDER BY `mallname` 

并且

SELECT mallname, COUNT( * ) AS Count
FROM `malls`
INNER JOIN Mal_Client_Relationship ON Mal_Client_Relationship.m_Id = malls.m_Id
INNER JOIN clients ON Mal_Client_Relationship.id_user = clients.id_user
INNER JOIN dates ON dates.date_id = Mal_Client_Relationship.date_id
WHERE confirmcode = 'y' && EndDate >= CURRENT_DATE( ) || count(*) = 0
GROUP BY `mallname`
ORDER BY `mallname` 

SELECT mallname, COUNT( * ) AS Count
FROM `malls`
INNER JOIN Mal_Client_Relationship ON Mal_Client_Relationship.m_Id = malls.m_Id
INNER JOIN clients ON Mal_Client_Relationship.id_user = clients.id_user
INNER JOIN dates ON dates.date_id = Mal_Client_Relationship.date_id
WHERE confirmcode = 'y' && EndDate >= CURRENT_DATE( ) || count(mallname) = 0
GROUP BY `mallname`
ORDER BY `mallname` 

阐明其背后的逻辑。当计数达到60(60个客户端)时,我需要禁用mallname。我在php中这样做,这是有效的。但是我需要包含带有0计数的mallname(这意味着商城还没有客户链接到它。

希望一切都有意义......

1 个答案:

答案 0 :(得分:1)

您遇到的问题是某些群组(商城名称)在计数为零时被删除。这个问题的一个解决方案是首先选择所有商城名称,然后LEFT JOIN将此结果选择为每个商城名称分组获得的结果。

SELECT DISTINCT m.mallname, COALESCE(t.Count, 0)
FROM `malls` m LEFT JOIN
(
    SELECT mallname, COUNT( * ) AS Count
    FROM `malls`
    INNER JOIN Mal_Client_Relationship ON Mal_Client_Relationship.m_Id = malls.m_Id
    INNER JOIN clients ON Mal_Client_Relationship.id_user = clients.id_user
    INNER JOIN dates ON dates.date_id = Mal_Client_Relationship.date_id
    WHERE confirmcode = 'y' && EndDate >= CURRENT_DATE( ) || HAVING count(*) = 0
    GROUP BY `mallname`
    ORDER BY `mallname`
) t
ON m.mallname = t.mallname