SELECT COUNT(*)GROUP BY输出零行

时间:2015-04-19 08:20:39

标签: sql database postgresql

我的数据库中的表:

CREATE TABLE items (
  id serial NOT NULL,
  user_id integer NOT NULL,
  status smallint
);

CREATE TABLE phones (
  phone character varying,
  users integer[]
);

我的查询找到状态= 1的电话号码:

SELECT phones.phone, COUNT(*) AS "count" 
FROM phones,items 
WHERE phones.phone = ANY (Array['7924445544', '8985545444'])
AND   items.user_id = ALL (phones.users) AND items.status = 1
GROUP BY phones.phone;

查询:

   phone    | count
------------+------
 7924445588 |     3

需要ZERO计数:

   phone    | count 
------------+-------
 8985545444 |     0
 7924445544 |     3

如何获得?

4 个答案:

答案 0 :(得分:0)

你不应该在查询中这样做。但是,如果你想要这样做,那就很容易了:

WITH phone_seek AS(
   SELECT '8985545444' AS phone
   UNION ALL
   SELECT '7924445588 '
)
SELECT  phone_seek.phone, COUNT(items.id) AS "count"
FROM 
  phones_seek
  JOIN phones
    ON phones_seek.phone = phones.phones
  CROSS JOIN items
WHERE 
  items.user_id = ALL (phones.users) AND items.status = 1 
GROUP BY phones.phone;

答案 1 :(得分:0)

创建不存在的行有点棘手。 (其中有数十亿,至少......) 如果手机不存在,请使用带有选择的UNION ALL来提供您想要的结果。

<current query>
UNION ALL
select '8985545444',0
from one_row_table where not exists (select 1 from phones
                                     where phones.phone = '8985545444')

修改 如果电话号码确实存在但未满足WHERE子句条件,请使用相关子选项进行计数:

SELECT phones.phone,
       (select count(*) from items
        where items.status = 1
          and items.user_id = phones.users) as "Count"
FROM phones
WHERE phones.phone = ANY (Array['7924445544', '8985545444'])

答案 2 :(得分:0)

Count是一个聚合函数,通常数据库引擎在没有符合条件的行时产生计数。

您的查询没有产生结果的原因是在db和group by中包含了您的phones.phone字段。

1)对此的廉价解决方案是仅选择count(*)作为您的应用程序     已经知道电话号码了:

SELECT  COUNT(*) AS "count"
FROM phones, items
WHERE phones.phone = '8985545444'
  AND items.user_id = ALL (phones.users) AND items.status = 1 ;

2)理想的解决方案是处理0结果的应用程序     由db。返回。

3)如果您需要db来完成所有工作,您可以使用以下内容:

SELECT  phones.phone, COUNT(*) AS "count"
FROM phones, items
WHERE phones.phone = '8985545444'
  AND items.user_id = ALL (phones.users) AND items.status = 1 
GROUP BY phones.phone;
UNION ALL
select '8985545444',0
from one_row_table where not exists (select 1 from phones
                                     where phones.phone = '8985545444')

答案 3 :(得分:0)

我不熟悉PostreSQL的数组语法,但这似乎只是一个简单的外连接:

SELECT phones.phone, COUNT(items.user_id) AS "count" 
FROM phones LEFT JOIN items 
  ON items.user_id = ALL (phones.users) 
 AND items.status = 1
WHERE phones.phone = ANY (Array['7924445544', '8985545444']) 
GROUP BY phones.phone;