SQL Query将标记数量计为0而不是NULL

时间:2017-08-09 00:39:58

标签: mysql sql

我的3个表格包含以下字段:

tags
----
id
name

photos
------
id
name
path
toDelete
star
flag

photo_tags
----------
photoId
tagId

我的查询目前是:

SELECT tags.id, tags.name, tagsCount.tagsCount FROM tags LEFT JOIN
(
    SELECT photo_tags.tagId, count(*) as tagsCount
    FROM `tags`
    INNER JOIN photo_tags ON tags.id = photo_tags.tagId
    GROUP BY photo_tags.tagId
) as tagsCount
ON tagsCount.tagId = tags.id

我回来了:

1 | Bob | NULL
2 | Bernie | 2 
3 | Harold | 1
4 | Jim | 5

因为bob没有出现在photo_tags中,所以它是NULL。我该怎么做那个0呢?

在这种情况下,子查询也是正确的用法吗?

2 个答案:

答案 0 :(得分:2)

replace更改为SELECT tags.id, tags.name, IFNULL(tagsCount.tagsCount,0) FROM tags LEFT JOIN ( SELECT photo_tags.tagId, count(*) as tagsCount FROM `tags` INNER JOIN photo_tags ON tags.id = photo_tags.tagId GROUP BY photo_tags.tagId ) as tagsCount ON tagsCount.tagId = tags.id 。 COALESCE语句选择第一个非空值。 https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#function_coalesce

答案 1 :(得分:1)

使用<T : Throwable><out Throwable>如果KClass<T>IFNULL(),那么IFNULL(check_exp, replace)将替换check_exp

NULL

你的子查询对我来说也很好。