Postgres 如何创建一个函数以在查询中使用

Postgres how can I create a function to use inside a query

我对 postgres 比较陌生,使用的是 9.4 版。我在 Java 中有一个简单的函数,有人告诉我如果让 postgres 做它会更有效率。我的函数接受一个整数和一个来自数据库的字符串数据并转换它们。这是我的函数:注意它接受一个整数和一个字符串

private static String difference(Integer i,String created_on) {
    String id = "";
    if (i < 60) {
      ...
        }
        else if (i >= 60 && i < 1440) {

       ....
    } 
else if (i >= 1440 && i < 10080) {

      ....

    } 
    else {

      ....
    }

    return id;
}

这是我的查询,现在 Created_on 是字符串,last_reply 是整数

"SELECT created_on as created_on,
last_reply as last_reply;

一旦数据来自数据库,我就把它放在一个循环中并通过这样做来转换它:

  for(i=0;i<10;i++) 
      {
                jo = new JSONObject();
                jo.put("last_reply", difference(rs.getInt("last_reply",
                                    rs.getString("created_on"))));
            }

如您所见,此处发生了数据转换

差异(rs.getInt("last_reply", rs.getString("created_on")

我现在的问题是如何复制该函数并将其保存在 postgres 中,以便我可以执行这样的查询

**

**"SELECT difference(last_reply,created_on) as newvalue, created_on as created_on,
    last_reply as last_reply;**

** 据我所知,从性能的角度来看,最好让数据库执行此操作,而不是使用 Java 循环遍历数据。任何建议都会很棒...

更新

该函数用于社交应用程序,以分钟为单位衡量发布内容的时间。如果少于 60 分钟,那么它会 return 类似于“6 分钟前等”,如果它在 60-1440 之间,那么它会 return “4 小时前等”。 .我已经计算出 If-else 语句中的计算,但没有包含它,这样代码看起来更像样。

这是完整的方法

private static String difference(Integer i,String created_on) {
    String id = "";
    if (i < 60) {

        if(i<1)
            id = "Now";

        else
            id = i + " min";
        }
        else if (i >= 60 && i < 1440) {

        i=(i/60);
        if(i==0)
        {i=1;}
        id = i + " hrs";
    } else if (i >= 1440 && i < 10080) {

        i=(i/1440);
        id = i + " day(s)";

    }
    else {
  // Posted longer than 7 days so Created_On will show date created
 // Passed down to the id String
        id = created_on;

    }

    return id;
}

不确定 Java 差异函数的数据类型是什么,但您可以通过以下两种方式之一来实现。从 Postgres 中将数据集拉入 Java,然后通过将两个值传递给您的函数来找到差异,然后将该结果集用于任何目的。

另一种方法是直接在 Postgres 中创建一个函数,然后从您的查询中调用该函数。

创建函数:

CREATE FUNCTION intDifference(integer, integer) RETURNS integer
    AS 'select  - ;'
    LANGUAGE SQL
    IMMUTABLE
    RETURNS NULL ON NULL INPUT;

在查询中使用函数:

SELECT intDifference(last_reply,created_on) as newvalue, created_on as created_on, last_reply as last_reply
FROM SOME_TABLE;