使用 IFNULL 将 NULL 设置为零
我有一个表,其中的字段包含整数或 NULL
。
parent_id
2
4
6
NULL
NULL
45
2
我该如何添加 IFNULL 语句,以便用 0
而不是 NULL
填充 ans_count
?
这是我的 SQL 代码:
...
(SELECT parent_id AS pid, COUNT(*) AS ans_count
FROM qa
GROUP BY parent_id) AS n
更新
下面是完整的 SQL - 感谢大家的耐心等待。
SELECT *
FROM qa
JOIN user_profiles
ON user_id = author_id
LEFT JOIN (SELECT cm_id,
cm_author_id,
id_fk,
cm_text,
cm_timestamp,
first_name AS cm_first_name,
last_name AS cm_last_name,
facebook_id AS cm_fb_id,
picture AS cm_picture
FROM cm
JOIN user_profiles
ON user_id = cm_author_id) AS c
ON id = c.id_fk
LEFT JOIN (SELECT parent_id AS pid, COUNT(*) AS ans_count
FROM qa
GROUP BY parent_id) AS n
ON id = n.pid
WHERE id LIKE '%'
ORDER BY id DESC
I have a table in which a field contains an integer or NULL
.
parent_id
2
4
6
NULL
NULL
45
2
How would I go about adding an IFNULL statement so that ans_count
will be populated with 0
instead of NULL
?
Here is my SQL code:
...
(SELECT parent_id AS pid, COUNT(*) AS ans_count
FROM qa
GROUP BY parent_id) AS n
UPDATE
Full SQL below - thanks to all for your patience.
SELECT *
FROM qa
JOIN user_profiles
ON user_id = author_id
LEFT JOIN (SELECT cm_id,
cm_author_id,
id_fk,
cm_text,
cm_timestamp,
first_name AS cm_first_name,
last_name AS cm_last_name,
facebook_id AS cm_fb_id,
picture AS cm_picture
FROM cm
JOIN user_profiles
ON user_id = cm_author_id) AS c
ON id = c.id_fk
LEFT JOIN (SELECT parent_id AS pid, COUNT(*) AS ans_count
FROM qa
GROUP BY parent_id) AS n
ON id = n.pid
WHERE id LIKE '%'
ORDER BY id DESC
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
编辑:基于完整查询的新信息
您指定的查询中计数可能为空的原因是因为左联接将在不匹配的记录上返回空值。因此子查询本身不会返回空计数(因此出现所有响应和混乱)。您需要在最外层的 select 中指定 IFNULL,如下所示:
OLD RESPONSE
您能否更详细地解释一下您所看到的以及您期望看到的内容?计数不能返回 NULL。
运行这组查询,您将看到计数始终为 2。您可以更改 NULL Parent_ids 的显示方式(如 NULL 或 0),但计数本身将始终返回。
EDIT: NEW INFO BASED ON FULL QUERY
The reason the counts can be null in the query you specify is because a left join will return nulls on unmatched records. So the subquery itself is not returning null counts (hence all the responses and confusion). You need to specify the IFNULL in the outer-most select, as follows:
OLD RESPONSE
Can you explain in more detail what you are seeing and what you expect to see? Count can't return NULLs.
Run this set of queries and you'll see that the counts are always 2. You can change the way the NULL parent_ids are displayed (as NULL or 0), but the count itself will always return.
我没有测试这个,但我认为它会起作用
I didn't test this, but I think it will work
只需将其包含在您的声明中即可:
Simply wrap it around your statement:
您是否尝试过仅计算parent_id?
Have you tried just counting the parent_id's?
您可以发布展示您正在谈论的行为的实际数据和完整查询吗?根据我的经验,
COUNT(*)
永远不能为 NULL。Count(*) 可以返回 null 吗?
COUNT(*) 总是返回结果吗?
Can you post actual data and full query which exhibits the behavior you are talking about? In my experience,
COUNT(*)
can never be NULL.Can Count(*) ever return null?
Does COUNT(*) always return a result?