gpt4 book ai didi

mysql - SQL 查询将标签数计数为 0 而不是 NULL

转载 作者:太空宇宙 更新时间:2023-11-03 11:36:25 26 4
gpt4 key购买 nike

我的 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?

在这种情况下使用子查询是否正确?

最佳答案

tagsCount.tagsCount 更改为 COALESCE (tagsCount.tagsCount, 0)。 COALESCE 语句选择第一个非空值。 https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#function_coalesce

关于mysql - SQL 查询将标签数计数为 0 而不是 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45579937/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com