如何做 SUM 而不是 UNION

How to do a SUM instead of a UNION

我有以下查询来获得两个不同的计数:

  select count(*)  
  from title_title where tv_show_id is null
union
  select count(distinct tv_show_id) 
  from title_title where tv_show_id is not null

有没有一种简单的方法可以在 SQL 内将两者相加而不是在它之外进行相加?

由于两个查询使用相同的 table,您可以在聚合函数中将 where 子句转换为 case 表达式,然后添加结果。注意count,像大多数聚合函数一样忽略了nulls,所以这可以相对整洁地完成:

SELECT COUNT(CASE WHEN tv_show_id IS NULL THEN 1 END) +
       COUNT(DISTINCT tv_show_id) -- nulls are ignored anyway
FROM   title_title

请原谅 MSSQL 的回答,但我相信你应该能够在 MySQL:

中做到这一点(或非常相似的事情)
SELECT  (COUNT(tt.*) + COUNT(tt2.tv_show_id)) AS Total
FROM    title_title tt
    JOIN title_title tt2 ON tt.tv_show_id = tt2.tv_show_id
WHERE   tt.tv_show_id IS NULL
    AND tt2.tv_show_id IS NOT NULL

执行 JOIN 回到 table,从每个(tt.*tt2.tv_show_id)中获取计数并以这种方式求和。