首页 > 解决方案 > 如果 id 不为空,Mysql 计数

问题描述

我想从响应表中计算未读消息。问题是,当根据where语句中的id不存在消息时,它会计数为0并返回一行。该行不得返回。任何建议如何解决这个问题?

SELECT m.*, COUNT(mr.id) as total_unread 
FROM `message` m 
LEFT JOIN message_response mr ON (mr.message_id = m.id) AND mr.read = 0
WHERE m.performance_report_id = :id

如果没有找到消息,上述语句将返回。

NULL    NULL    NULL    NULL    NULL    NULL    NULL    0

标签: mysql

解决方案


把你m.performance_report_id = :idON Clause而不是where

SELECT m.*, COUNT(mr.id) as total_unread 
FROM `message` m 
LEFT JOIN message_response mr ON (mr.message_id = m.id) AND mr.read = 0
and m.performance_report_id = :id

推荐阅读