mysql count过滤空值,使其不将空数据计入条数
当mysql中使用count分组统计数据时,如果不想使空值计入总数,我们可以使用如下解决方法1,首先看如下两个查询语句:(1)SELECTt.id, t.meetStyle, t.title,count(p.id) AS personCount,count(f.id) AS fileCountFROM meeting_info tLEFT
·
当mysql中使用count分组统计数据时,如果不想使空值计入总数,我们可以使用如下解决方法
1,首先看如下两个查询语句:
(1)
<pre name="code" class="sql">SELECT
t.id, t.meetStyle, t.title,
count(p.id) AS personCount,
count(f.id) AS fileCount
FROM meeting_info t
LEFT JOIN meeting_person p
ON t.id= p.mId
LEFT JOIN meeting_file f
ON t.id=f.mId where t.ID='info0000000234'
(2)
SELECT
t.id, t.meetStyle, t.title,
count(DISTINCT p.id) AS personCount,
count(DISTINCT f.id) AS fileCount
FROM meeting_info t
LEFT JOIN meeting_person p
ON t.id= p.mId
LEFT JOIN meeting_file f
ON t.id=f.mId where t.ID='info0000000234' 这两条语句虽然只有一词之差,实际却相差千里,因为第一条语句的查询结果和如下语句查询结果相同:
SELECt f1.id,f1.MeetStyle,f1.title,f1.personCount,f2.fileCount from
( SELECT
t.id, t.meetStyle, t.title,
count(p.id) AS personCount
FROM meeting_info t
LEFT JOIN meeting_person p
ON t.id= p.mId
where t.ID='info0000000234' ) f1
,
(SELECT
t.id, t.meetStyle, t.title,
count(f.id) AS fileCount
FROM meeting_info t
LEFT JOIN meeting_file f
ON t.id=f.mId where t.ID='info0000000234') f2
2,由上面两种查询可以看出,count(DISTINCT p.id)具有过滤当数值为空的情况,使其不再计入总数
更多推荐



所有评论(0)