Postgres子查询返回1行,但exists返回false

时间:2016-10-25 00:10:59

标签: sql postgresql count subquery exists

我不确定这是怎么回事。这是NOT EXISTS测试的内部查询。

 SELECT subq.* FROM(
        SELECT distinct on("contractId") "contractId", clients.id, clients.name, "contractHistory".status, "contractHistory"."timeStamp", first_value("contractHistory"."id") over(partition by "contractId" order by "timeStamp" desc) as window
          FROM "contractHistory", "clients", "contracts"
          WHERE "contractHistory"."contractId" = "contracts"."id"
          AND "clients"."id" = "contracts"."clientId"
          AND contracts.opened < now()
          AND contracts.expires > now() + '1 day'::interval
        ) AS subq
      WHERE subq.status = 'Signed'
      AND subq.id = 12345
  ;
  

(1行)

如果我将外部SELECT更改为count(subq。*),我得到:

  

计数

 1

到目前为止一切顺利。但是在SELECT EXISTS和

中包装整个原始查询
  

存在

     

˚F

这是为什么?我需要将此查询包装在外部查询中:

SELECT * FROM "clients" AS c WHERE status = 'Active' AND NOT EXISTS(
SELECT subq.* FROM(
            SELECT distinct on("contractId") "contractId", clients.id, clients.name, "contractHistory".status, "contractHistory"."timeStamp", first_value("contractHistory"."id") over(partition by "contractId" order by "timeStamp" desc) as window
              FROM "contractHistory", "clients", "contracts"
              WHERE "contractHistory"."contractId" = "contracts"."id"
              AND "clients"."id" = "contracts"."clientId"
              AND contracts.opened < now()
              AND contracts.expires > now() + '1 day'::interval
            ) AS subq
          WHERE subq.status = 'Signed'
          AND subq.id = c.id
);

即使内部查询返回1行,它也会为外部查询返回一行。

编辑以添加SELECT EXISTS:

 SELECT EXISTS(
      SELECT subq.* FROM(
        SELECT distinct on("contractId") "contractId", clients.id, clients.name, "contractHistory".status, "contractHistory"."timeStamp", first_value("contractHistory"."id") over(partition by "contractId" order by "timeStamp" desc) as window
          FROM "contractHistory", "clients", "contracts"
          WHERE "contractHistory"."contractId" = "contracts"."id"
          AND "clients"."id" = "contracts"."clientId"
          AND contracts.opened < now()
          AND contracts.expires > now() + '1 day'::interval
        ) AS subq
      WHERE subq.status = 'Signed'
      AND subq.id = 12345
  );
  

存在

     

˚F   (1排)

只是为了完整性:

SELECT 1 FROM(
        SELECT distinct on("contractId") "contractId", clients.id, clients.name, "contractHistory".status, "contractHistory"."timeStamp", first_value("contractHistory"."id") over(partition by "contractId" order by "timeStamp" desc) as window
          FROM "contractHistory", "clients", "contracts"
          WHERE "contractHistory"."contractId" = "contracts"."id"
          AND "clients"."id" = "contracts"."clientId"
          AND contracts.opened < now()
          AND contracts.expires > now() + '1 day'::interval
        ) AS subq
      WHERE subq.status = 'Signed'
      AND subq.id = 12345
  

?列?

     

(0行)

0 个答案:

没有答案