在psql中运行并引用一次函数 [英] Run and reference function once in psql

查看:103
本文介绍了在psql中运行并引用一次函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,可以返回ID表以进行复杂的节点查找。

I have a function that returns table of IDs for a complex lookup of nodes.

使用此函数的查询多次要求使用-有没有办法一次获取并命名函数结果-使代码更简洁:

The queries using this function, require it more than once - is there a way to get and name the function result once - to make the code cleaner:

SELECT channels.name
FROM channels
WHERE (
      channels.to_id   IN (SELECT matchingNodes(1,1)) 
  AND channels.from_id IN (SELECT matchingNodes(1,1))
); 

我正在使用PostgreSQL 11,查询变得更加复杂(对的调用更多matchingNodes

I am using PostgreSQL 11 and the queries get more complicated (more calls to matchingNodes)

推荐答案

您可以使用常用表格表达式

假定将matchnodes函数定义为 returns table(...),您也可以避免第二个子通过选择函数的列两次来查询。设置返回函数应该在 FROM 子句中使用。

Assuming the function matchingnodes is defined as returns table (...) you can also avoid a second sub-query by selecting the columns of the function twice. Set returning functions should be used in the FROM clause to begin with.

因此,不要使用 select matchingnodes(1,1)使用 select id,matchingnodes(1,1)中的id(假设函数返回的列已命名 id ):

So instead of select matchingnodes(1,1) use select id, id from matchingnodes(1,1) (assuming the column returned by the function is named id):

with nodes as (
  select id, id
  from matchingnodes(1,1)
) 
select ch.name
from channels ch
where (ch.to_id, ch.from_id) in (select id, id,
                                 from nodes);

这篇关于在psql中运行并引用一次函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆