当我的 sql return 没有行时,我如何 return 0?

How do I return 0 when my sql returns with no rows?

select a, count (b) 
from table1 where b in ( select distict b from table2) 
and table1.dated>=DATE('yy/mm/dd') 
group by a;

在上面的 SQL 中,当我有 count(b)>0 时它是 returns 列,但是当 count=0 时没有返回行

我确实尝试了 UNION、NULLIF() 和 SELECT(SELECT()) 作为某种东西,但没有任何效果。

如果计数等于 0,我希望返回 0。

https://www.db-fiddle.com/#&togetherjs=2AkxeMUrPF

您可以使用:

select table1.a, count(DISTINCT table2.b) 
from table1
LEFT JOIN table2
  ON table1.b = table2.b
  AND table1.dated>=DATE('yy/mm/dd') -- this comparision is simply incorrect
group by table1.a

我们可以通过让查询保证它来确保查询 return 是一行。

下面是一个从内联视图中仅检索一行的示例 i

然后外连接到另一个内联视图s,获得不同的值列表。

然后是 table1 的另一个外部连接。

SELECT t.a
     , COUNT(t.b) AS cnt
  FROM ( SELECT 1 AS n ) i 
  LEFT
  JOIN ( SELECT DISTINCT r.b 
           FROM table2 r
       ) s
  LEFT
  JOIN table1 t
    ON t.b      = s.b
   AND t.dated >= ...
 GROUP
    BY i.n
     , t.a

如果内联视图sreturn没有行,查询应该return

 a      cnt
 ----   ---
 NULL     0