PostgreSQL - 结合函数的SELECT和RETURN VALUE

时间:2016-07-04 08:12:50

标签: sql postgresql function select

在我的数据库中,我有一个表“Datapoint”,其中包含两列“Id”(整数)和“Description”(字符变化)。 Table "Datapoint"

然后我有一个表“Logging”,其中包含三列“Id”(整数),“Dt”(没有时区的时间戳)和“Value”(双精度)。Table "Logging"

我还有以下功能:

CREATE OR REPLACE FUNCTION count_estimate(query text)
  RETURNS integer AS
$BODY$ DECLARE rec   record;ROWS  INTEGER;BEGIN FOR rec IN EXECUTE 'EXPLAIN ' || query LOOP ROWS := SUBSTRING(rec."QUERY PLAN" FROM ' rows=([[:digit:]]+)');EXIT WHEN ROWS IS NOT NULL;END LOOP;RETURN ROWS;END $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

此函数返回SELECT-Query找到的估计条目数,例如: SELECT count_estimate('SELECT * FROM“记录”WHERE“Id”= 3')将返回2.

我现在想把表“Datapoint”上的SELECT查询与我的函数的返回值结合起来,这样我的结果就像这样:

ID  |   Description |   EstimatedCount
1   |   Datapoint 1 |   3
2   |   Datapoint 2 |   4
3   |   Datapoint 3 |   2
4   |   Datapoint 4 |   1    

我的SELECT查询应该如下所示:

SELECT
 "Datapoint"."Id",
 "Datapoint"."Description",

(SELECT count_estimate ('SELECT * FROM "Logging" WHERE "Logging"."Id" = "Datapoint"."Id"')) AS "EstimatedCount"

 FROM
 "Datapoint"

所以我的问题是为我的目的编写一个有效的SELECT查询。

2 个答案:

答案 0 :(得分:0)

怎么样:

SELECT
 "Datapoint"."Id",
 "Datapoint"."Description",

count_estimate ('SELECT * FROM "Logging" WHERE "Logging"."Id" = "Datapoint"."Id"') AS "EstimatedCount"

 FROM
 "Datapoint"

答案 1 :(得分:0)

除了你需要提供"Datapoint"."Id"

的值之外,你几乎做对了
SELECT
   "Datapoint"."Id",
   "Datapoint"."Description",
   count_estimate(
      'SELECT * FROM "Logging" WHERE "Logging"."Id" = ' || "Datapoint"."Id"
   ) AS "EstimatedCount"
FROM "Datapoint";