admin

从没有行的计数中获取0值

sql

我有选择:

SELECT c FROM (
    SELECT "candidate_id" as id, count("candidate_id") as c
    FROM "Applicaions"
    GROUP BY "candidate_id"
) as s WHERE id= _SOME_ID_;

但这仅在返回一个值count > 0。如果count = 0没有返回任何内容。如何获得0没有任何申请的“候选人”?

有表格“候选人”。
如果候选人没有应用程序或不存在,我需要得到0。

编辑

我现在有了:

SELECT COALESCE ((SELECT count("candidate_id") as c
FROM "Applicaions" WHERE "candidate_id"=_SOME_ID_
GROUP BY "candidate_id"), 0);

它完美地工作。但是有可能写得更简单还是最好的解决方案?我应该创建任何索引吗?


阅读 178

收藏
2021-05-10

共1个答案

admin

您需要在PostgreSQL中使用COALESCE函数http://developer.postgresql.org/pgdocs/postgres/functions-
conditional.html

本质上,您需要告诉SQL返回时如何处理NULLsie 。NULL``0

2021-05-10