如何为Postgres中的选定行将列值增加1?

时间:2018-09-28 14:54:21

标签: sql postgresql

我有一个postgres表,其中包含列idnameitemcounter。现在,我想将counter的值增加<对于用户所属的行,strong> 1 。

我尝试做这样的事情,但是语法错误

UPDATE Items set counter = counter + 1 WHERE users = 'Tony';

对于用户 Tony 所属的所有行,这应该使counter的值增加 1 。类似于

初始

id | name | item    | counter
1  | Tony  | car    | 1
2  | Tony  | bike   | 1
3  | Ray   | car    | 1
4  | Ray   | bike   | 1
5  | Tony  | cycle  | 1

最终

id | name | item    | counter
1  | Tony  | car    | 2
2  | Tony  | bike   | 2
3  | Ray   | car    | 1
4  | Ray   | bike   | 1
5  | Tony  | cycle  | 2

但是我的查询语法错误。我在做什么错?

3 个答案:

答案 0 :(得分:2)

您的driver = browser.Driver() 查询包含UPDATE而不是users

demo: db<>fiddle

name

答案 1 :(得分:1)

列名称可能错误。试试这个:

UPDATE Items set counter = counter + 1 WHERE name= 'Tony';

答案 2 :(得分:0)

对于 rowdata1 输入

    select   employee_id, accrual_group_code, accrual_type, start_date,accru_date from z_123  where (doc_id =0 or doc_id is null ) order by accru_date
            LOOP
                            employeeId   = rowdata1.employee_id;
                            accrualgroupcode   = rowdata1.accrual_group_code;
                            accrualtype   = rowdata1.accrual_type;
                            accrudate   = rowdata1.accru_date;
                            select (cast(date_trunc('month', accrudate::date) as date) - interval '1 month')::date into startdate;

                            update  z_123 set company_id = 2 , doc_id= 2 where employee_id = employeeId
                            and  accrual_group_code = accrualgroupcode and  accrual_type = accrualtype and accru_date = accrudate;                                
            END LOOP;