2016-06-10 35 views
1

我正在嘗試在我的網站上執行條件更新。 每當用戶單擊某個鏈接時,數據庫中的全局計數器變量會自行增加。PSQL中的條件更新聲明

併發症是,當計數器數量超過我記錄的網站數量時,我希望計數器回到1.我有一個更新聲明,但它不工作,我看不出爲什麼。

#Increment global counter, set it back to one when it exceeds the number of websites on record 
cursor.execute("UPDATE url_reroute_counter SET counter_num = "+ 
        " CASE"+ 
         " WHEN counter_num>(SELECT count(*) FROM url_reroute_targeturl)"+ 
          " THEN counter_num = 1"+ 
         " ELSE"+ 
          " counter_num = counter_num+1"+ 
        " END"+ 
        " WHERE name_of_counter = 'url_count'")` 

運行這段代碼讓我以下異常:

django.db.utils.ProgrammingError: column "counter_num" is of type integer but expression is of type boolean 
    LINE 1: UPDATE url_reroute_counter SET counter_num = CASE WHEN coun... 
                 ^
    HINT: You will need to rewrite or cast the expression. 

我不習慣在任何SQL語言,所以這裏的任何HLEP表示讚賞使用條件語句。

+0

我覺得比較合適的標籤是postgresql – e4c5

回答

1

您的查詢應該如下

cursor.execute("UPDATE url_reroute_counter SET counter_num = "+ 
       " CASE"+ 
        " WHEN counter_num>(SELECT count(*) FROM url_reroute_targeturl)"+ 
         " THEN 1"+ 
        " ELSE"+ 
         " counter_num+1"+ 
       " END"+ 
       " WHERE name_of_counter = 'url_count'")` 

而且順便說一句,在多線Python字符串,你並不需要所有的+號。這個:https://stackoverflow.com/a/10660443/267540

+0

現在我覺得很傻,這很明顯。 – GreenGodot

+0

碰巧每個人\ – e4c5