2013-04-28 64 views
2

我正在爲我的一個朋友在一個小型藝術畫廊網站工作,並已決定由於各種原因與PostgreSQL一起去。到目前爲止,一切運行良好,但我遇到了一些小障礙。問題出在下面的功能上。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; 
+0

您忘記了您的Postgres版本以及您收到的錯誤消息。 – 2013-04-28 01:51:17

+0

是的,你是對的。我使用9.1在Mint 14 MATE上運行。 – WellNow 2013-04-28 02:15:04

回答

1

不能表限定列進行更新,但你可以(而且必須,在這種情況下)中使用的表達表資格列:

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。

+0

顯示我對PSQL的新感受。更改了更新語句並刪除了聲明塊。現在效果很好。謝謝歐文。 – WellNow 2013-04-28 02:17:54

+0

@WellNow:該功能很好地完成。讓你旅行的部分是棘手的。 – 2013-04-28 02:21:10