PSQL

时间:2016-06-10 11:47:50

标签: django postgresql

我试图在我的网站上进行有条件的更新。 每当用户单击某个链接时,数据库中的全局计数器变量就会递增。

复杂的是,当计数器数量超过我记录的网站数量时,我希望计数器返回1.我有一个更新声明,但它不起作用,我看不出原因。< / p>

#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。

1 个答案:

答案 0 :(得分: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