3

我正在为我的一个朋友开发一个小型艺术画廊网站,出于各种原因决定使用 PostgreSQL。到目前为止,一切都运行良好,但我遇到了一个小障碍。问题在于以下功能。

我的viewcount专栏有歧义问题。冲突发生在更新语句和返回表之间。viewcount除了将返回的表列更改为类似视图或创建另一个函数来更新计数之外,我不太确定如何解决此问题。

我对 SQL 的基本知识来自我使用 MSSQL 的工作。

create or replace function submission_getone
(
    int         -- submissionid
    ,boolean    -- upcount
    ,int        -- mmask
    ,int        -- statemask
)
returns table
(
    submissionid int
    ,galleryid int
    ,gallerytitle varchar(100)
    ,createdby int
    ,createdbyname varchar(32)
    ,alteredby int
    ,alteredbyname varchar(32)
    ,createdon timestamp
    ,alteredon timestamp
    ,title varchar(100)
    ,content text
    ,file1 varchar(64)
    ,viewcount int
    ,mlevel int
    ,typecode int
    ,statecode int
)
as
$$
declare
    _submissionid   alias for $1;
    _upcount        alias for $2;
    _mmask          alias for $3;
    _statemask      alias for $4;
begin
    -- because the member may not want to see specific content (mmask)
    -- and because the submitter my have not published the content (statemask),
    -- include mmask and statemask in the where clause

    -- referenced this for aliases in an update
    -- http://stackoverflow.com/questions/11369757/postgres-wont-accept-table-alias-before-column-name
    if _upcount = true then
        update submission us set 
            viewcount = viewcount + 1 
        where us.submissionid = _submissionid 
            and (us.mlevel & _mmask) = us.mlevel
            and (us.statecode & _statemask) = us.statecode;
    end if;

    return query
    select
        s1.submissionid
        ,s1.galleryid
        ,coalesce(g1.title, 'Orphan')::varchar(100) as gallerytitle
        ,s1.createdby
        ,m1.accountname
        ,s1.alteredby
        ,m2.accountname
        ,s1.createdon
        ,s1.alteredon
        ,s1.title
        ,s1.content
        ,s1.file1
        ,s1.viewcount
        ,s1.mlevel
        ,s1.typecode
        ,s1.statecode
    from submission s1
    left join gallery g1 on s1.galleryid = g1.galleryid
    join member m1 on s1.createdby = m1.memberid
    join member m2 on s1.alteredby = m2.memberid
    where s1.submissionid = _submissionid
            and (s1.mlevel & _mmask) = s1.mlevel
            and (s1.statecode & _statemask) = s1.statecode;
end;
$$
language plpgsql;
4

1 回答 1

2

您不能对要更新的列进行表限定,但您可以(并且在这种情况下必须)对使用的表达式中的列进行表限定:

SET  viewcount = us.viewcount + 1

顺便说一句,在 Postgres 8.0 或更高版本中,您可以(并且应该)使用参数名称而不是别名:

CREATE OR REPLACE FUNCTION submission_getone (
  _submissionid int
 ,_upcount boolean
 ,_mmask int
 ,_statemask int
)

...并摆脱这个:

declare
    _submissionid   alias for $1;
    _upcount        alias for $2;
    _mmask          alias for $3;
    _statemask      alias for $4;

RETURNS TABLE表示您至少获得了 Postgres 8.4。

于 2013-04-28T02:00:44.470 回答