Oracle Count未显示0

时间:2014-01-27 11:40:41

标签: sql oracle count

我对以下查询有点问题:

SELECT 
    country.country_id AS "COUNTRY_ID", count(con.medal_id) AS "GOLD"
FROM
    country country 
LEFT OUTER JOIN
  contestant con on con.country_id = country.country_id
AND con.medal_id = 1
LEFT OUTER JOIN 
  event e on e.event_id = con.event_id 
WHERE  e.og_id = 1 
GROUP BY
    country.country_id
ORDER BY
    country.country_id

我正在尝试将查询显示为以下内容:

COUNTRY_ID       GOLD
---------- ----------
         1          1 
         2          2 
         3          0 
         4          0 

然而,在我当前的查询中,它显示了这个:

COUNTRY_ID       GOLD
---------- ----------
         1          1 
         2          2 

如果我将WHERE e.og_id = 1更改为AND e.go_id = 1

结果将如下:

COUNTRY_ID       GOLD
---------- ----------
         1          1 
         2          5 
         3          0 
         4          3 

此结果与没有此行相同:

LEFT OUTER JOIN 
  event e on e.event_id = con.event_id 
AND  e.og_id = 1 

如果有人需要更多信息,请告诉我。

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

将子句e.og_id = 1移动到JOIN应该可以解决问题:

SELECT 
    country.country_id AS "COUNTRY_ID", count(con.medal_id) AS "GOLD"
FROM
    country country 
LEFT OUTER JOIN contestant con 
  on con.country_id = country.country_id AND con.medal_id = 1
LEFT OUTER JOIN event e 
  on e.event_id = con.event_id AND e.og_id = 1 
GROUP BY
    country.country_id
ORDER BY
    country.country_id

或者,您可以明确允许NULL:

SELECT 
    country.country_id AS "COUNTRY_ID", count(con.medal_id) AS "GOLD"
FROM
    country country 
LEFT OUTER JOIN contestant con 
  on con.country_id = country.country_id AND con.medal_id = 1
LEFT OUTER JOIN event e 
  on e.event_id = con.event_id 
WHERE e.og_id = 1 or e.og_id IS NULL
GROUP BY
    country.country_id
ORDER BY
    country.country_id

答案 1 :(得分:1)

WHERE将过滤掉左连接创建的空值。将where移动到连接条件:

SELECT 
    country.country_id AS "COUNTRY_ID", count(con.medal_id) AS "GOLD"
FROM
    country country 
      LEFT OUTER JOIN contestant con 
        on con.country_id = country.country_id
        AND con.medal_id = 1
     LEFT OUTER JOIN 
       event e on e.event_id = con.event_id 
       AND e.og_id = 1 
GROUP BY
    country.country_id
ORDER BY
    country.country_id;

或者,将过滤器移回where子句,处理LEFT JOIN返回NULL的情况。

    country country 
      LEFT OUTER JOIN contestant con 
        on con.country_id = country.country_id
     LEFT OUTER JOIN 
       event e on e.event_id = con.event_id 
   WHERE 
       (con.country_id IS NULL OR con.medal_id = 1)
       AND 
       (e.event_id IS NULL OR e.og_id = 1)

有关此behaviour here

的更多信息