postgresql 为 select 中的每一行调用一个函数 - Postgres
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27991286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call a function for each row in select - Postgres
提问by Gilbert
I have a function called "getList(date)". This function returns me a items list (with several columns) from the date inputted in the parameter.
我有一个名为“getList(date)”的函数。这个函数从参数中输入的日期返回一个项目列表(有几列)。
If I call:
如果我打电话:
SELECT * FROM getList('12/31/2014');
It works fine. It returns me a list with the date, the item name and the price.
它工作正常。它返回一个包含日期、项目名称和价格的列表。
Something like this:
像这样的东西:
date item_description price
-----------------------------------------------
12/31/2014 banana 1
12/31/2014 apple 2.5
12/31/2014 coconut 3
But I have another table with the dates that I want to search for.
但是我有另一个表,里面有我想要搜索的日期。
So, I want to select all the dates from that table and, for each row returned, I want to call my function "getList" to have a result like this:
因此,我想从该表中选择所有日期,对于返回的每一行,我想调用我的函数“getList”以获得如下结果:
date item_description price
-----------------------------------------------
12/28/2014 banana 0.5
12/28/2014 apple 1.5
12/28/2014 coconut 2
12/31/2014 banana 1
12/31/2014 apple 2.5
12/31/2014 coconut 3
I don't know exactly how to do it. Of course my data is not a fruit list. This is just to explain the whole thing easier.
我不知道具体该怎么做。当然我的数据不是水果清单。这只是为了更容易地解释整个事情。
Thank you very much.
非常感谢你。
回答by Craig Ringer
Correct way - LATERAL
join
正确方式——LATERAL
加入
The correct way to do this is with a lateral query (PostgreSQL 9.3 or newer):
正确的方法是使用横向查询(PostgreSQL 9.3 或更新版本):
SELECT d."date", f.item_description, f.price
FROM mydates d,
LATERAL getList(d."date") f;
See the manual.
请参阅手册。
Legacy way - SRF in SELECT
传统方式 - SRF 中 SELECT
In older versions you must use a PostgreSQL extension with some ... quirky ... properties, support for set-returning functions in the SELECT
-list. Do not use this unless you know you must support PostgreSQL 9.2 or older.
在旧版本中,您必须使用具有一些...古怪...属性的 PostgreSQL 扩展,支持SELECT
-list中的 set-returning 函数。除非您知道必须支持 PostgreSQL 9.2 或更早版本,否则不要使用它。
SELECT d."date", (getList(d."date").*
FROM mydates d;
This may result in multiple-evaluation of the getList
function, once for each column of the output.
这可能会导致对getList
函数进行多次评估,对输出的每一列进行一次评估。