使用created_at搜索时,PostgreSQL结果不正确

时间:2017-08-30 07:53:59

标签: sql postgresql

我有以下查询:

SELECT
  COUNT(sr.id) AS total,
  COUNT(sr.id) FILTER (where (raw #>> '{survey, declined}' IS NULL) OR (raw #>> '{survey, declined}' = 'false')) AS completed,
  COUNT(sr.id) FILTER (WHERE (raw #>> '{survey, declined}' = 'true')) AS denied
FROM survey_results sr
LEFT JOIN clients c ON c.id = sr.client_id
LEFT JOIN facilities f ON f.client_id = c.id
WHERE
    sr.created_at >= '2005-07-01T08:00:00+00:00' AND 
    sr.created_at <= '2005-08-02T07:59:59+00:00' AND
    4 IS NULL OR sr.client_id = 4 AND 
    NULL IS NULL OR f.id = NULL
;

问题是没有使用那些created_at过滤器。它还返回在不同时间创建的记录。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

你需要括号:

WHERE (sr.created_at >= '2005-07-01T08:00:00+00:00' AND 
       sr.created_at <= '2005-08-02T07:59:59+00:00'
      ) AND
      (4 IS NULL OR sr.client_id = 4) AND 
      (NULL IS NULL OR f.id = NULL)

虽然没有必要,但我会使用带有tz的显式时间戳来编写tis并简化逻辑:

WHERE (sr.created_at >= '2005-07-01T08:00:00+00:00'::timestamptz AND 
       sr.created_at < '2005-08-02T08:00:00+00:00'::timestamptz
      ) AND
      (4 IS NULL OR sr.client_id = 4) AND 
      (NULL IS NULL OR f.id = NULL)

答案 1 :(得分:1)

有多个AND和一个OR使where子句中的任何一个工作,  你需要用括号分组子句,如:

Caused by: javax.naming.NamingException: [LDAP: error code 1 - 000004DC: LdapErr: DSID-0C0909AF, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v3839

答案 2 :(得分:1)

删除4 IS NULLNULL IS NULL,并使用括号:

 WHERE (sr.created_at >= '2005-07-01T08:00:00+00:00' AND 
    sr.created_at <= '2005-08-02T07:59:59+00:00') 
    AND
    (sr.client_id = 4 OR f.id = NULL)