2016-06-10 62 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